help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: member returns list (was: Re: To `boundp' or not to `boundp'?)


From: Drew Adams
Subject: RE: member returns list (was: Re: To `boundp' or not to `boundp'?)
Date: Tue, 1 Sep 2015 23:21:15 -0700 (PDT)

> It looks like this: (member ELT LIST)
> 
> When is it beneficial to, instead of just getting
> a `t' on a hit, to get a list that consists of ELT and
> everything eastward of ELT, in LIST?

When that is what you want/need. ;-)

> The `car' example I provided may look cool (?) but it
> isn't anything that cannot be done with "memberp",
> because obviously the car is known, otherwise one
> wouldn't be able to search for it.

Sure, if you just want the element you're testing for, then
(car (member 'foo xs)) is no better than
(and (memberp 'foo xs)  'foo)

(In the second example, if the element needs to be
computed, let-bind it to avoid computing it twice.)

But maybe you want the next element after `foo':
(cadr (member 'foo xs))

Or the element after `foo' or the first element if `foo' is
not in the list:
(or (cadr (member 'foo xs))  (car xs))

Or maybe you want to change `foo' to `bar' in the list:
(setcar (member 'foo xs) 'bar)

Or maybe you want to truncate the list after `foo':
(setcdr (member 'foo xs) ())

Or maybe you want to ensure that 'foo is at the head of
the list, adding it there if not already in the list:
(if (null xs)
    (setq xs  (list 'foo))
  (let ((tl  (member 'foo xs)))
    (unless (eq tl xs)
      (when tl (setcdr (nthcdr (1- (- (length xs) (length tl))) 
                               xs)
                       (cdr tl)))
      (setq xs  (cons 'foo xs))))
  xs)

Or the same thing for any list variable and element:
(defun put-at-head (list-var element)
  (let* ((lis  (symbol-value list-var))
         (tl   (member element lis)))
    (cond ((null lis) (set list-var (list element)))
          ((not (eq tl lis))
           (when tl (setcdr (nthcdr (1- (- (length lis) (length tl)))
                                    lis) 
                            (cdr tl)))
           (set list-var (cons element lis)))))
  (symbol-value list-var))

You get the idea.  Often, if you care about the list structure
it is because you are modifying it (destructive operations).
(Not always - e.g., (cadr (member 'foo xs)).)
 
And yes, most other uses of `member' (and `memq') are just tests
for membership.  You can see this by grepping the Emacs Lisp sources.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]