Chuyển đến nội dung

Bài 16 · Functions and Closures

Functions and Parameters

Define Common Lisp functions with defun and its lambda list: required, &optional, &rest and &key parameters, defaults, supplied-p flags, and multiple return values.

Functions are the heart of Lisp. You have already written simple ones with defun; this lesson goes deep on the lambda list (the parameter list) which in Common Lisp supports optional parameters, keyword parameters and rest parameters, and on a feature few other languages have: functions that return multiple values.

defun recap

LISP
(defun add (a b)
  "Return the sum of A and B."
  (+ a b))

(add 2 3)          ; => 5

A defun has a name, a lambda list, an optional docstring and a body. The body's last form is the return value. To leave early, use return-from with the function's name:

LISP
(defun first-negative (numbers)
  (dolist (n numbers nil)
    (when (minusp n)
      (return-from first-negative n))))

(first-negative '(3 5 -2 7))   ; => -2

Calling a function with the wrong number of arguments signals an error at run time (and a warning at compile time when it is visible).

Optional parameters

After &optional, parameters may be omitted. Each can have a default:

LISP
(defun greet (name &optional (greeting "Hello"))
  (format nil "~a, ~a!" greeting name))

(greet "Ada")            ; => "Hello, Ada!"
(greet "Ada" "Welcome")  ; => "Welcome, Ada!"

Without a default an omitted optional is NIL. A third element, the supplied-p variable, tells you whether the caller actually passed it, which is important when NIL is a legitimate value:

LISP
(defun connect (host &optional (port 80 port-supplied-p))
  (list host port port-supplied-p))

(connect "x")        ; => ("x" 80 NIL)
(connect "x" 80)     ; => ("x" 80 T)

Defaults can use earlier parameters: (&optional (end (length seq))).

Rest parameters

&rest collects all remaining arguments into a list:

LISP
(defun sum (&rest numbers)
  (apply #'+ numbers))

(sum 1 2 3 4)       ; => 10
(sum)               ; => 0

apply spreads a list back out as arguments: (apply #'+ '(1 2 3)) equals (+ 1 2 3). Treat the rest list as read-only and do not mutate it; implementations may share it with the caller's argument list.

Keyword parameters

&key parameters are passed by name, in any order, and are always optional:

LISP
(defun make-user (&key name (role :guest) email)
  (list :name name :role role :email email))

(make-user :name "Ada" :email "[email protected]")
;; => (:NAME "Ada" :ROLE :GUEST :EMAIL "[email protected]")

(make-user :role :admin :name "Bo")
;; => (:NAME "Bo" :ROLE :ADMIN :EMAIL NIL)

Keywords make call sites self-documenting, which is why standard functions use them everywhere (:test, :key, :start). Like optionals, they take a default and a supplied-p variable: (&key (verbose nil verbose-p)).

Passing an unknown keyword is an error unless the lambda list has &allow-other-keys (or the caller passes :allow-other-keys t):

LISP
(make-user :nme "typo")     ; ERROR: unknown keyword :NME

You can rename the variable used inside: (&key ((:name n))), though that is rarely needed.

Mixing parameter kinds

The order is always: required, &optional, &rest, &key, &aux.

LISP
(defun demo (a b &optional (c 3) &rest more &key (d 4) &allow-other-keys)
  (list a b c more d))

Mixing &optional with &key is risky: a keyword symbol can be swallowed as an optional value. As a rule, use either optionals or keys for the same function, not both. &aux declares local variables, an old style now replaced by let.

A stand-in for lambda-list binding

This JavaScript stand-in (not Lisp) implements a small version of how arguments are matched to a lambda list, supporting required, &optional with defaults and supplied-p, &rest and &key with errors for wrong calls. It makes the rules concrete.

JS Stand-in: binding a lambda list

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Multiple return values

A Lisp function can return several values at once with values. This avoids packaging results in a list or struct when you simply want a pair:

LISP
(defun min-and-max (numbers)
  (values (reduce #'min numbers)
          (reduce #'max numbers)))

(min-and-max '(3 9 2))     ; REPL shows: 2  then 9

Callers who want only the first value ignore the rest automatically, so adding extra values never breaks old code. To capture them:

LISP
(multiple-value-bind (lo hi) (min-and-max '(3 9 2))
  (format nil "from ~a to ~a" lo hi))       ; => "from 2 to 9"

(multiple-value-list (floor 7 2))            ; => (3 1)
(nth-value 1 (floor 7 2))                    ; => 1
(multiple-value-setq (q r) (floor 17 5))     ; assigns existing variables

Standard functions use this heavily: floor returns quotient and remainder, gethash returns a value and a found flag, parse-integer returns the number and the position where parsing stopped, get-decoded-time returns nine values. If a form that normally returns several values is used as a plain argument, only the first value is used.

(values) with no arguments returns zero values; a REPL prints nothing for it. Compare that with NIL, which is one value.

Documentation and introspection

LISP
(documentation 'greet 'function)
(describe 'greet)
(function-lambda-expression #'greet)    ; implementation dependent

Add a docstring to every public function; editors show it when you type the function name.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What is the correct order of lambda-list parts?

    Required parameters come first, then &optional, &rest, &key and &aux.
  2. 2. What is the purpose of a supplied-p variable?

    It distinguishes 'not passed' from 'passed NIL'.
  3. 3. What does (multiple-value-bind (a b) (floor 7 2) (list a b)) return?

    floor returns quotient 3 and remainder 1; multiple-value-bind captures both.
  4. 4. What happens when you call a function with an unknown keyword argument?

    Unknown keywords signal an error by default.
  5. 5. How do you return early from the function search-it?

    defun establishes a block named after the function; return-from leaves it.

Summary

  • A lambda list supports required, &optional, &rest, &key and &aux parameters, in that order.
  • Optionals and keys take defaults and supplied-p variables; unknown keywords are errors.
  • &rest collects the remaining arguments into a list; apply spreads a list into arguments.
  • values returns multiple values; multiple-value-bind, multiple-value-list, nth-value receive them.
  • return-from exits a function early; add docstrings to document your functions.

Next: Lambda and Higher-Order Functions

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.