views:

675

answers:

5

Can anyone tell me how to work with the parameters stored in the value specified by &rest.

I've read around a lot and it seems as if authors only know how to list all the parameters as so.

(defun test (a &rest b) b)

This is nice to see, but not really that useful.

The best I've found so far is to use first, second, and so on to get the parameter you are looking for.

(defun test (a &rest b)
    (first b))

I noticed this method stops working at the tenth parameter, but the specification (from what I've read) supports a minimum of 50. Even if the chances are slim that I'll use 50 parameters, I'd like to know how to access them all.

Thanks

+7  A: 

Rest parameter is just a list. You can handle it using normal list operations.

(defun test (a &rest b))
  (dolist (s b)
    (when (> s 1)
      (print s)
      (do-something-else b)))
Dev er dev
+2  A: 

The FIRST, SECOND and so on accessor functions are "just" utility functions on top of CAR/CDR or NTH. SO, I guess, the answer to your specific question is "use NTH or ELT" (or build your own specific acccessor functions).

If you want, you can define an ELEVENTH as:

(defun eleventh (list) (nth 10 list))

I find, however, that I mostly use &REST arguments when there's 0 or more things I want to do something with, not really caring about the specific position of a given argument in the &REST list. That usually entails using LOOP, DO or DOLIST to traverse the arguments and do something with each one; the MAP family or (occasionally) REDUCE.

Vatine
+4  A: 

Actually the function is useful. You only have to try it.

CL-USER 1 > (defun test (a &rest b) b)
TEST

CL-USER 2 > (test 1 2 3 4)
(2 3 4)

So you see that B is just a list of the arguments. So every list and sequence operation applies. There is nothing magic. There are functions to access the NTH element, functions to remove elements, etc..

In the Common Lisp HyperSpec the relevant functions are listed:

14. The Conses Dictionary

17. The Sequences Dictionary

For a basic Lisp tutorial check out the book by Touretzky:

Common Lisp: A Gentle Introduction to Symbolic Computation

The book is downloadable in PDF and Postscript. It teaches basic Common Lisp.

Rainer Joswig
Thanks for the link to the gentle introduction. I've browsed through the first couple chapters and I have to say that I really wish this was the first programming book I read. It's very well done.
Douglas Brunner
+1  A: 

You could also use destructuring-bind:

(defun my-function (&rest arguments)
  (destructuring-bind (a b &rest c) arguments
    (format nil "~A,~A followed with ~A" a b c)))

CL-USER> (my-function 1 2 "Give" 'me "more" 'arguments!!)
==> "1,2 followed with (Give ME more ARGUMENTS!!)"
Mark Cox
A: 

I just have a recursive iterate to go through them all, I guess dolist is better but I like using the old fashioned way

Isaiah