Lisp/Functions

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search

Functions

(defun func-name (parameters) body)

(defun func-name (parameters)
  "Documentation"
  body)

Parameters

Required Parameters

The first parameters listed are always required.

Optional Parameters

The parameters following '&optional' are optional. They can take two forms:

  • param-name: Just the name, will default to NIL.
  • (param-name default): The name and the default.
  • (param-name default param-name-supplied-p): The name, the default, and a variable that will be true if the param was specified. By convention, it is always param-supplied-p.

Optional parameters can refer back to earlier parameters in their default value.

Rest Parameters

The parameter following '&rest' suck up the remaining arguments into a list.

(defun format (stream string &rest values) ...)
(defun + (&rest numbers) ...)

Keyword Parameters

The parameters following '&key' are the keyword parameters. Note that they are also sucked up by the &rest parameter, if any.

The keyword parameters are just like the optional parameters, in that you can specify just the name, the name and the default value, or the name, default value, and -supplied-p value.

Keyword parameter specifiers can also accept an initial external name:

(:length l)

This will cause the internal name of the param to be l, while the external name is :length.

Keyword parameters can refer back to earlier parameters in their default value just like optional parameters can.

Keyword parameters are specified by the series :param-name value.

Documentation

This is human-readable documentation, like Python's doc strings.

Body

The body consists of any number of expressions. The last value is returned, unless the RETURN-FROM special operator is used somewhere.

Getting a Reference to a Function

Use the FUNCTION special operator:

(function +)
#'+

Using a Reference to a Function

Use APPLY or FUNCALL.

(funcall #'+ 1 2 3)
(apply #'+ '(1 2 3))

Anonymous Functions

(lambda (params) body)

Treat this as the name of a function that would do the same.

((lambda (x y) (+ x y)) 1 2) ; Rarely done.
(funcall #'(lambda (x y) (+ x y)) 1 2)

See Also