Notes From Practical Common Lisp
A function’s parameter list defines the variables that will be used to hold the arguments passed to the function when it’s called. If the function takes no arguments, the list is empty, written as (). Different flavors of parameters handle required, optional, multiple, and keyword arguments. I’ll discuss the details in the next section. If a string literal follows the parameter list, it’s a documentation string that should describe the purpose of the function. When the function is defined, the documentation string will be associated with the name of the function and can later be obtained using the DOCUMENTATION function. To define a function with optional parameters, after the names of any required parameters, place the symbol &optional followed by the names of the optional parameters. A simple example looks like this:
(defun foo (a b &optional c d) (list a b c d))
it’s useful to know whether the value of an optional argument was supplied by the caller or is the default value. you can add another variable name to the parameter specifier after the defaultvalue expression. This variable will be bound to true if the caller actually supplied an argument for this parameter and NIL otherwise. By convention, these variables are usually named the same as the actual parameter with a “-supplied-p” on the end.
(defun foo (a b &optional (c 3 c-supplied-p))
To give a function keyword parameters, after any required, &optional, and &rest parameters you include the symbol &key and then any number of keyword parameter specifiers, which work like optional parameter specifiers.
(defun foo (&key ((:apple a)) ((:box b) 0) ((:charlie c) 0 c-supplied-p))
(list a b c c-supplied-p))
All the functions you’ve written so far have used the default behavior of returning the value of the last expression evaluated as their own return value. This is the most common way to return a value from a function.
No comments:
Post a Comment