Open In App

Rest Parameters in LISP

Improve
Improve
Like Article
Like
Save
Share
Report

LISP Function‘s parameters list has a basic aim of declaring the variables which will receive the arguments that are passed in the function. Normally parameter list contains a basic list of variable names, those parameters are called “required parameters”. If a function is called, for every required parameter it should be supplied with one individual argument, if it’s called with more or fewer arguments, LISP will show an error.

Types of parameters in the parameters list

  • Required parameters
  • Optional Parameters
  • Rest Parameters
  • Keyword Parameters

Rest Parameters

Sometimes a function needs to take a variable number of arguments, for illustration, take the + function in LISP which takes the variable number of arguments and is not just limited to 2 arguments, possible calls for the + function includes : 

(+)
(+ 9)
(+ 5 2)
(+ 3 7 1)

So as you can see the parameter list for + function may look similar to this : 

(defun + (&rest numbers) ...) 

But you may doubt that we can also write this functions which would take variable number of arguments by having multiple optional parameters, but such incredible number of handling parameters is not considered a right LISP attiquette.

The syntax for defining Rest Parameters:

To define any rest parameter in the function, add the symbol: &rest before the name of the parameter, When you call a function all the arguments after the required and optional parameters are grouped together into a list and they become the value for &rest parameter.

Example:

Let’s create a function where r1 & r2 will be required parameters and anything other than that would be rest parameters.

(defun rest_example (r1 r2 &rest rest)...)

Now as we know any arguments after the required and optional parameters are grouped into a list of rest parameters, So lets print those rest parameters along with our required parameters.

(format t "Required parameters: ~d & ~d.~%" r1 r2)
(format t "Rest parameters: ~d~%" rest)

Now let’s call this function by passing just required parameters and second time by passing with rest parameters also

(rest_example 50 80)
(rest_example 40 60 75 67 10 30)

Code : 

Lisp




(defun rest_example (r1 r2 &rest rest)
  (format t "Required parameters: ~d & ~d.~%" r1 r2)
  (format t "Rest parameters: ~d~%" rest))
  
(rest_example 50 80)
(terpri)
(rest_example 40 60 75 67 10 30)


Output : 

Required parameters: 50 & 80.
Rest parameters: NIL

Required parameters: 40 & 60.
Rest parameters: (75 67 10 30)

As you may see at our first call we don’t pass any rest parameters hence the value of the rest parameter was NIL, but when we call the function with rest parameters all our arguments other than the required parameters are grouped into a list of rest parameters.


Last Updated : 29 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads