LISP: Keyword parameters, supplied-p -


at moment i'm working through "practical common lisp" peter seibel.

in chapter "practical: simple database" (http://www.gigamonkeys.com/book/practical-a-simple-database.html) seibel explains keyword parameters , usage of supplied-parameter following example:

(defun foo (&key (b 20) (c 30 c-p)) (list b c c-p)) 

results:

(foo :a 1 :b 2 :c 3)  ==> (1 2 3 t) (foo :c 3 :b 2 :a 1)  ==> (1 2 3 t) (foo :a 1 :c 3)       ==> (1 20 3 t) (foo)                 ==> (nil 20 30 nil) 

so if use &key @ beginning of parameter list, have possibility use list of 3 parameters name, default value , third if parameter been supplied or not. ok. looking @ code in above example:

(list b c c-p) 

how lisp interpreter know c-p "supplied parameter"?

let's reindent function foo:

(defun foo (&key                  (b 20)                  (c 30 c-p))    (list b c c-p)) 

if indent see function has 3 keyword parameters: a, b , c. these available in body of function.

for keyword parameter c there variable declared c-p t or nil depending whether c has been passed when foo gets called.

a keyword parameter can declared 1 of following options:

  1. as single variable name
  2. a list of variable name , default value
  3. a list of variable name, default value , variable show whether parameter has been passed or not when function gets called

the supplied-p particularly interesting when 1 wants see whether value comes call or default value:

(defun make-my-array (size &key (init-value nil init-value-supplied-p))    (if init-value-supplied-p        (make-array size :initial-element init-value)        (make-array size))) 

now user can init elements nil:

(make-my-array 10 :init-value nil) 

here default value , supplied value can both nil, need make difference. variable init-value-supplied-p makes possible see whether nil value of variable init-value comes default or function call.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -