Functions(v2 · en)

注:本概念在 v2 无独立正文,正文沿自 v1(未修订即沿用——显式标注而非静默回退)。

Concept

Functions parameterize expressions. fn builds an anonymous function value; defun defines a global function slot. Fixed parameters match exactly, and & rest collects the remaining arguments into a list. Functions are first-class: they can be bound, passed around, and called on demand.

(defun square [x] (* x x))
(println (square 6))
(println (funcall #'square 7))
(println ((fn [x y] (+ x y)) 3 4))
(defun collect [head & remaining] [head remaining])
(println (collect 1 2 3))

Expected stdout:

36
49
7
[1 (2 3)]

Zio is a Lisp-2: names live in two namespaces, function slots and value slots. #'square ((function square)) reads the function value and funcall calls it; a defun'd square works in head position directly, while a bare reference in value position is a typed rejection — preventing "passed a function name where a variable was meant" from slipping through silently. Multiple body forms run in order and the last expression's value is the return value; loop / recur provide tail-position iteration (see the language reference).

Design notes

"Functions are first-class values" and "function slots / value slots are separate" are a deliberate pair of trade-offs: first-classness makes higher-order functions, callbacks and composition everyday tools, while Lisp-2 keeps a defun'd name callable no matter what variable shadows it. Common Lisp chose Lisp-2; Scheme and Clojure chose Lisp-1 — more uniform, at the cost that (f x) must find a function value under f in the environment. Zio offers both sides explicitly: defun (slot) and defn (value-semantics alias) make separate promises; see section 5 of the syntax reference.

Going further

Parameterization is the minimal reuse mechanism: when "add a constant" becomes (make-adder 4), the parameter k has left its argument expression behind yet stays alive inside the returned function — a binding that outlives the call is a closure, see Closures. The contrast edge between this concept and closures (input alone determines output vs. the captured environment also shapes behavior) is exactly what that edge exists to teach.

前序概念

后续概念

相关实验

无