Lisp - Optional Parameters



You can define a function with optional parameters. To do this you need to put the symbol &optional before the names of the optional parameters.

Let us write a function that would just display the parameters it received.

Example

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

main.lisp

; define a function with optional parameters
(defun show-members (a b &optional c d) (write (list a b c d)))
; call the method with an optional parameter
(show-members 1 2 3)
; terminate printing
(terpri)
; call method with all optional parameter
(show-members 'a 'b 'c 'd)
; terminate printing
(terpri)
; call method with no optional paramter
(show-members 'a 'b)
; call method with all optional parameter
(terpri)
(show-members 1 2 3 4)

Output

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

(1 2 3 NIL)
(A B C D)
(A B NIL NIL)
(1 2 3 4)

Please note that the parameter c and d are the optional parameters in the above example.

Example - Sum of Multiple Numbers

Update the file named main.lisp and type the following code in it. In this code, we're getting sum of numbers passed.

main.lisp

; define a function with optional parameter
(defun sum (a b &optional c) 
   ; check if c is not defined
   (if(not c)
      ; get sum of two numbers   
      (write (+ a b))
	  ; otherwise get sum of all numbers
      (write (+ a b c))
   ))

; terminate printing
(terpri)
; call method with no optional parameter
(sum 1 2)
; terminate printing
(terpri)
; call method with optional parameter
(sum 1 2 3)

Output

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

3
6

Example - Multiplication of Multiple Numbers

Update the file named main.lisp and type the following code in it. In this code, we're getting sum of numbers passed.

main.lisp

; define a function with optional parameter
(defun product (a b &optional c) 
   ; check if c is not defined
   (if(not c)
      ; get product of two numbers 
      (write (* a b))
      ; otherwise get product of all numbers
      (write (* a b c))
   ))
; terminate printing
(terpri)
; call method with no optional parameter
(product 1 2)
; terminate printing
(terpri)
; call method with optional parameter
(product 1 2 3)

Output

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

2
6
lisp_functions.htm
Advertisements