Sunday, October 18, 2009

Functions In Common Lisp

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))
 Of course, you’ll often want a different default value than NIL. You can specify the default value by replacing the parameter name with a list containing a name and an expression.
 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))

 Lisp lets you include a catchall parameter after the symbol &rest. If a function includes a &rest parameter, any arguments remaining after values have been doled out to all the required and optional parameters are gathered up into a list that becomes the value of the &rest parameter.

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))
Whenever more than one flavor of parameter is used, they must be declared in the order I’ve discussed them: first the names of the required parameters, then the optional parameters, then the rest parameter, and finally the keyword parameters.Combining &optional and &key parameters yields surprising enough results that you should probably avoid it altogether.You can safely combine &rest and &key parameters, but the behavior may be a bit surprising initially.
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