Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Optional Parameters in LISP

  • Last Updated : 15 Nov, 2021

Optional Parameters are the parameters that are optional in the function. We can put optional parameters whenever the arguments are not necessary. If we keep the optional parameters in a function and pass the values, then the values are taken in place of optional parameters. If values are not passed, then optional parameters will take NIL and return NIL. If we want to put optional parameters as arguments, then put &optional before the names of the optional parameters.

Function Syntax:

(defun function_name (parameter1,parameter2,.......,parameter n.... &optional )
other statements))
(call function value1,value2,.,value n, optional values)

Example: LISP program to display all its passed parameters.

Lisp




;create a function named display
;pass the 2 parameters and optional as three parameters
(defun display (val1 val2 &optional op1 op2 op3) (write (list val1 val2 op1 op2 op3)))
 
;pass the all values
(display 10 20 30 40 50)
(terpri)
 
;pass only two values
(display 10 20 )
(terpri)
 
;pass only three values
(display 10 20 30)
(terpri)
 
;pass only four values
(display 10 20 30 40)
(terpri)

Output:



(10 20 30 40 50)
(10 20 NIL NIL NIL)
(10 20 30 NIL NIL)
(10 20 30 40 NIL)

Example 2: LISP Program to get the sum of numbers

Lisp




;create a function named sum
;pass the 2 parameters and optional as three parameters
(defun sum (val1 val2 &optional op1 op2 op3) (write ( + val1 val2 op1 op2 op3)))
 
;pass the all values to get sum
(sum 10 20 30 40 50)
(terpri)

Output:

150
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!