绑定:def / defun / fn / let / set!

顶层与局部绑定、匿名函数、可变参数、多 arity 子句与解构绑定。

(def the-answer 42)
(defun square [x] (* x x))
(square the-answer)

fn 是匿名函数;let 并行绑定(init 看外层,ADR-051),顺序依赖用 let*。

(def outer-x 10)
(let ((x 2) (y outer-x)) (+ x y))               ;; 并行:y 的 init 看外层 → 12
(let* ((a 1) (b (inc a)) (c (inc b))) [a b c])  ;; 顺序:[1 2 3]

可变参数 & rest。

(defun greet [name & titles]
  (str "hi " name " " (if (nil? titles) "" titles)))
(greet "Ada" :dr)

set! 重绑定已存在的名字。

(def counter 0)
(set! counter (+ counter 1))
counter

多 arity 子句

fn / defun 的参数表可以是多个子句 ( [params] body… )…:按源顺序首匹配——精确子句要求实参个数相等,& rest 子句要求不小于。零匹配发出条件 no-matching-arity(payload 为期望 arity 向量与实参个数),可被 with-handlers 捕获。

(defun pair ([x] [x x]) ([x y] [x y]))
[(pair 1) (pair 1 2)]
((fn ([& args] (count args)) ([x y] :two)) 1 2)

决策:defmacro 与 defmethod 保持严格单 arity 符号参数——多子句/解构参数显式拒绝。

解构绑定

let / let* 与 fn/defun 参数支持模式绑定,可任意嵌套:

(let [[a b & rest :as all] [1 2 3 4]]
  [a b rest all])
(let [{:keys [name] :as u} {:name "zio"}]
  [name u])

向量模式语义:rest 恒为 list(与 & rest 一致);元素不足报 index out of bounds;多余元素丢弃。map 模式当前支持 :keys 与 :as=;:strs= / :syms / :or 显式拒绝(留作后续)。loop 保持严格符号绑定(recur 不能重绑 pattern)。