Wednesday, May 05, 2004

Passing variable arguments of a function

Yesterday I was struggling with the &rest parameter, mainly due to my
ignorance and inexperience. I have used the &rest parameter in the
past and it works very easily. For instance, the function below will
just return its arguments. The &rest parameter is very useful in case
of variable arguments.

(defun foo (&rest args)

Evaluating the following

(foo 1 2 3) => (1 2 3)

(foo 'a 'b 1 2) => (a b 1 2)

Even though I have used this in functions before, I was having
problems passing the &rest arguments of one function to another. So I
jumped on the #lisp channel and asked the experienced folks there,
and they said, just use 'apply', and the bulb in head lit up, of course.

Here is a very simple example of passing the &rest parameter to the
&rest of another funtion.

(defun add (&rest args)
(apply #'+ args))

(defun sub (&rest args)
(apply #'- args))

(defun mul (&rest args)
(apply #'* args))

(defun div (&rest args)
(apply #'/ args))

(defun basic-calc (fun &rest args)
(apply fun args))

Now evaluating

(add 1 2 3) => 6

(basic-calc 'add 1 2 3) => 6

I have used APPLY and FUNCALL many times without realizing the
implications of how powerful these are. The solution is so simple
that it never comes to mind.


Post a Comment

Subscribe to Post Comments [Atom]

<< Home