Chuyển đến nội dung

Bài 17 · Functions and Closures

Lambda and Higher-Order Functions

Treat functions as values in Common Lisp: lambda expressions, #' and the function special form, funcall and apply, Lisp-2 namespaces, flet, labels and function composition.

In Common Lisp, functions are first-class values: you can create them anywhere, store them in variables, pass them to other functions and return them from functions. Functions that take or return functions are called higher-order functions, and they are why Lisp code stays short. This lesson explains lambda, the #' notation, funcall and apply, the Lisp-2 rule that makes them necessary, local functions with flet and labels, and how to build functions like compose.

lambda: functions without names

lambda creates an anonymous function:

LISP
(lambda (x) (* x x))          ; a function object
((lambda (x) (* x x)) 5)      ; => 25   call it immediately (legal, rarely used)
(mapcar (lambda (x) (* x x)) '(1 2 3))   ; => (1 4 9)

A lambda has the same lambda list as defun (see Functions and Parameters). In fact defun is essentially "make a lambda and attach it to a name".

#' and the function special form

Common Lisp is a Lisp-2: every symbol can have a variable value and a function definition separately. When a name appears in function position, Lisp looks up its function definition. When you want the function as a value, you ask for it with function, usually abbreviated #':

LISP
(function car)         ; => #<FUNCTION CAR>
#'car                  ; same thing
#'(lambda (x) x)       ; same as (lambda (x) x); the #' is optional for lambda
(mapcar #'car '((a 1) (b 2)))    ; => (A B)

Without #', (mapcar car ...) would look up the variable car and fail with "unbound variable".

funcall and apply

If you have a function in a variable, calling (f 3) would look for a function named f. Use funcall to call a function object:

LISP
(defparameter *op* #'+)
(funcall *op* 1 2 3)          ; => 6
(funcall #'max 3 9 2)         ; => 9
(let ((f (lambda (x) (* 2 x))))
  (funcall f 21))              ; => 42

apply is like funcall but takes its last argument as a list of arguments:

LISP
(apply #'+ '(1 2 3))          ; => 6
(apply #'+ 1 2 '(3 4))        ; => 10     leading arguments, then a list
(apply #'max '(4 8 1))        ; => 8

A function name as a symbol also works: (funcall 'car '(1 2)) => 1, because symbols can be looked up at call time. Prefer #' for compile-time checking and speed.

Lisp-2 in one example

LISP
(defun double (x) (* x 2))        ; function namespace
(defparameter double 10)          ; variable namespace: no conflict

(double 5)                        ; => 10  (the function)
double                            ; => 10  (the variable)
(list double #'double)            ; => (10 #<FUNCTION DOUBLE>)

This is why you can name a variable list, as in (defun f (list) (length list)), without breaking the function list. Scheme and Clojure are Lisp-1s and need no funcall; this course's Mini-Lisp is a simplified Lisp-1 for the same reason.

Try these ideas on the Mini-Lisp (a JavaScript stand-in interpreter, not SBCL; its funcall exists but function and variable names share one namespace):

JS Mini-Lisp: lambda, funcall, apply

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

No output.

Returning functions

Functions can build and return other functions:

LISP
(defun make-multiplier (n)
  (lambda (x) (* x n)))

(defparameter *triple* (make-multiplier 3))
(funcall *triple* 7)                       ; => 21
(mapcar (make-multiplier 10) '(1 2 3))     ; => (10 20 30)

The inner lambda remembers n; that is a closure, the subject of the next lesson.

Composition and friends

The standard library offers a few function builders:

LISP
(complement #'evenp)               ; function that is true for odd numbers
(remove-if (complement #'evenp) '(1 2 3 4))   ; => (2 4)
(constantly 42)                    ; a function that ignores its args and returns 42
(funcall (constantly 42) 1 2 3)    ; => 42
(identity 5)                       ; => 5

Common Lisp has no built-in compose, but it is a few lines to write, including any number of functions:

LISP
(defun compose (&rest fns)
  (if (null fns)
      #'identity
      (let ((f (car (last fns)))
            (rest-fns (butlast fns)))
        (lambda (&rest args)
          (reduce (lambda (acc fn) (funcall fn acc))
                  (reverse rest-fns)
                  :initial-value (apply f args))))))

(funcall (compose #'1+ #'abs) -5)          ; => 6    (abs first, then 1+)

The alexandria library provides compose, curry and rcurry ready-made.

Local functions: flet and labels

let makes local variables; flet makes local functions:

LISP
(flet ((square (x) (* x x))
       (cube (x) (* x x x)))
  (list (square 3) (cube 3)))         ; => (9 27)

Functions defined by flet cannot call each other or themselves, because their names are not visible inside their own bodies. When you need recursion or mutual calls, use labels:

LISP
(defun sum-to (n)
  (labels ((walk (i acc)
             (if (> i n)
                 acc
                 (walk (1+ i) (+ acc i)))))
    (walk 1 0)))

(sum-to 10)       ; => 55

Local functions keep helpers private, are fast, and can use the variables of the enclosing function directly.

Higher-order thinking: functions as arguments

Because functions are values, many problems become "write a general routine, take the specific bit as a function". Sorting with a custom order is the classic case:

LISP
(sort (list "pear" "fig" "banana") #'< :key #'length)
;; => ("fig" "pear" "banana")

(defun apply-n (fn n x)
  (dotimes (i n x)
    (setf x (funcall fn x))))

(apply-n #'1+ 5 0)                         ; => 5
(apply-n (lambda (v) (* v 2)) 10 1)        ; => 1024

Stand-in: composition and currying in JavaScript

JavaScript functions are Lisp-1 values, so this stand-in (plain JS, not Lisp) shows the same ideas without funcall.

JS Stand-in: compose, curry, complement

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

No output.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does #'car mean?

    #'x is shorthand for (function x), which returns the function object.
  2. 2. How do you call a function stored in the variable f?

    In a Lisp-2, (f ...) looks up a function named f; funcall calls the function object in the variable.
  3. 3. What does (apply #'+ 1 2 '(3 4)) return?

    apply spreads the last list: (+ 1 2 3 4) = 10.
  4. 4. Which form lets a local function call itself?

    labels makes the function names visible inside the function bodies; flet does not.
  5. 5. Why can you name a variable list without breaking (list 1 2)?

    This is the Lisp-2 property.

Summary

  • lambda makes anonymous functions; #' (function) gets a named function as a value.
  • funcall calls a function object with arguments; apply takes a list of arguments as its last argument.
  • Common Lisp is a Lisp-2, so functions and variables live in separate namespaces.
  • Functions can return functions; build helpers like compose or use alexandria.
  • flet defines local functions; labels allows recursion and mutual calls.

Next: Closures and Lexical Scope

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ị.