Lisp - Rest Parameters



Some functions need to take a variable number of arguments.

For example, the format function we are using needs two required arguments, the stream and the control string. However, after the string, it needs a variable number of arguments depending upon the number of values to be displayed in the string.

Similarly, the + function, or the * function may also take a variable number of arguments.

You can provide for such variable number of parameters using the symbol &rest.

The following example illustrates the concept −

Example

Create a new source code file named main.lisp and type the following code in it.

Update main.lisp and type the following code in it.

main.lisp

; define a function to print arguments
(defun show-members (a b &rest values) (write (list a b values)))
; call the show-members function with three parameters
(show-members 1 2 3)
; terminate printing
(terpri)
; call the show-members function with four parameters
(show-members 1 2 3 4)
; terminate printing
(terpri)
; call the show-members function with nine parameters
(show-members 1 2 3 4 5 6 7 8 9)

Output

When you execute the code, it returns the following result −

(1 2 (3))
(1 2 (3 4))
(1 2 (3 4 5 6 7 8 9))

Example

Update the source code file named main.lisp and type the following code in it.

Update main.lisp and type the following code in it.

main.lisp

; define a function to print arguments
(defun show-members (a b &rest values) (write (list a b values)))
; call the show-members function with four parameters
(show-members 'a 'b 'c 'd)
; terminate printing
(terpri)
; call the show-members function with two parameters
(show-members 'a 'b)

When you execute the code, it returns the following result −

(A B (C D))
(A B NIL)

Example

Updat the source code file named main.lisp and type the following code in it.

Update main.lisp and type the following code in it.

main.lisp

; define a function to print arguments
(defun show-members (a b &rest values) (write (list a b values)))
; call the show-members function with three parameters
(show-members 1.0 2.0 3.0)
; terminate printing
(terpri)
; call the show-members function with four parameters
(show-members 1.0 2.0 3.0 4.0)
; terminate printing
(terpri)
; call the show-members function with nine parameters
(show-members 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0)

When you execute the code, it returns the following result −

(1.0 2.0 (3.0))
(1.0 2.0 (3.0 4.0))
(1.0 2.0 (3.0 4.0 5.0 6.0 7.0 8.0 9.0))
lisp_functions.htm
Advertisements