Lisp - keyword Parameters
Keyword parameters allow you to specify which values go with which particular parameter.
It is indicated using the &key symbol.
When you send the values to the function, you must precede the values with :parameter-name.
The following example illustrates the concept.
Example
Create a new source code file named main.lisp and type the following code in it.
main.lisp
; define a function show-members to print list of arguments passed (defun show-members (&key a b c d ) (write (list a b c d))) ; call function with three parameters (show-members :a 1 :c 2 :d 3) ; terminate printing (terpri) ; call function with two parameters (show-members :a 1 :b 2)
Output
When you execute the code, it returns the following result −
(1 NIL 2 3) (1 2 NIL NIL)
Example
Update the source code file named main.lisp and type the following code in it.
main.lisp
; define a function show-members to print list of arguments passed (defun show-members (&key a b c d ) (write (list a b c d))) ; call function with three parameters (show-members :a 'p :b 'q :c 'r :d 's) ; terminate printing (terpri) ; call function with two parameters (show-members :a 'p :d 'q)
Output
When you execute the code, it returns the following result −
(P Q R S) (P NIL NIL Q)
Example
Update the source code file named main.lisp and type the following code in it.
main.lisp
; define a function show-members to print list of arguments passed (defun show-members (&key a b c d ) (write (list a b c d))) ; call function with three parameters (show-members :a 1.0 :c 2.0 :d 3.0) ; terminate printing (terpri) ; call function with two parameters (show-members :a 1.0 :b 2.0)
Output
When you execute the code, it returns the following result −
(1.0 NIL 2.0 3.0) (1.0 2.0 NIL NIL)
Advertisements