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

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

Re: How to remove verbosity from the data passing mechanism using alist


From: Pascal J. Bourguignon
Subject: Re: How to remove verbosity from the data passing mechanism using alist or plist ?
Date: Wed, 08 Dec 2010 04:49:05 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/23.2 (gnu/linux)

PJ Weisberg <pj@irregularexpressions.net> writes:

> I was trying to come up with an example to show how 'list' was like a
> bunch of 'cons's, but the part of my brain that can do recursion was
> in sleep mode, and then the best I came up with was
>
> (defun my-list( &rest args )
>   (if args
>       (cons (car args) (eval (cons 'my-list (cdr args))))
>     nil))

This is completely wrong:

(my-list '(+ 1 1) '(* 2 2) '(- 3 3))
--> ((+ 1 1) 4 0)

(list '(+ 1 1) '(* 2 2) '(- 3 3))
--> ((+ 1 1) (* 2 2) (- 3 3))


> and I didn't think was was clarifying *anything* if I had to use eval
> to while I was explaining cons.  ;-)
>
> P.S.:  For the benefit of lisp beginners who don't know, if args is
> '(1 2 3 4), then (cdr args) is '(2 3 4), and (cons 'my-list '(2 3 4))
> is '(my-list 2 3 4).  Doesn't that look like a function call?  eval
> treats it as such.


First, &rest gives a list to the parameter, therefore you should use
list processing functions such as endp, first and rest, not symbol or cons
processing functions such as null, car and cdr, when applying them on
the parameter.

Then, instead if using eval, you should use apply in this case:

  (defun my-list (&rest args)
     (if (endp args)
       '()
       (cons (first args) (apply (function my-list) (rest args)))))

or just build a copy of the parameter:

  (defun my-list (&rest args)
    (let* ((result (cons '() '()))
           (tail   result))
      (dolist (item args (cdr result))
        (setf (cdr tail) (cons item nil)
              tail       (cdr tail)))))

or just:

  (defun my-list (&rest args)
    (copy-list args))


(my-list '(+ 1 1) '(* 2 2) '(- 3 3))
--> ((+ 1 1) (* 2 2) (- 3 3))


-- 
__Pascal Bourguignon__                     http://www.informatimago.com/
A bad day in () is better than a good day in {}.


reply via email to

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