29

What does the &rest mean in this: (append &rest sequences)

I have finished the book "elisp_intro",but I didn't find the answer. I will be very grateful if you can help me.

dbr
  • 165,801
  • 69
  • 278
  • 343
hq.wrong
  • 353
  • 3
  • 5

3 Answers3

27

It indicates that the following argument is the "rest" argument. In the case of your example, sequences is the rest argument.

Unlike a normal argument, the rest argument will consume the "rest" of any parameters provided by the user. It is a way of making a function that accepts a variable number of arguments. Inside the function body, the argument will be a list containing all of the extra parameters.

So if you had a function that looked like (add &rest numbers), then you could call it like (add 1 2 3 4 5), and within the function the numbers argument would have the value (1 2 3 4 5).

Or for example, ((lambda (a &rest r) r) 1 2 3) ;=> (2 3)

Brian Burns
  • 20,575
  • 8
  • 83
  • 77
kenm
  • 23,127
  • 2
  • 43
  • 62
  • 5
    It's worth noting that the `apply` function works nicely in conjunction with the `&rest` feature, as `apply` requires its final argument to be an argument list. So if you need to accept a variable number of arguments in order to pass them into another function, these two features make that convenient to do. – phils Jan 01 '12 at 08:46
11

Any arguments following the &rest symbol in a function definition will be collected into a single list object. So in the case of (append &rest sequences), if you call the function:

(append 1) 

the variable sequences will be the list (1) in the body of the function. If you call it as

(append 1 2 3)

the variable sequences will be the list (1 2 3) in the body of the function. This is explained in the Elisp Reference manual, in the argument list node.

(info "(elisp)Argument List")
Brian Burns
  • 20,575
  • 8
  • 83
  • 77
Tyler
  • 9,872
  • 2
  • 33
  • 57
3

elisp/Common Lisp &rest is analogous to the *args parameter in Python

If you put this in your Common Lisp repl and call foo with varying numbers of arguments, you will see what's up quite quickly.

(defun foo (a b &rest trailing) 
  (format t "~a :: ~a :: ~a~%" a b trailing))
Paul Nathan
  • 39,638
  • 28
  • 112
  • 212