绑定与函数

def、let、defun 与 fn;函数是一等值,另有可变参数、多 arity 子句与解构绑定。

def 定义顶层名字;let 建立局部绑定;defun 定义函数(参数用向量)。

(def greeting "hello")
(let [a 2 b 3] (* a b))

(defun square [x] (* x x))
(square 12)

函数是一等值:可以传递、返回、存进数据结构。

(def twice (fn [f] (fn [x] (f (f x)))))
((twice square) 3)

(map square [1 2 3 4])
(filter odd? [1 2 3 4 5])
(reduce + 0 [1 2 3 4 5])

可变参数用 & rest 收集。

(defun my-list [first & rest] (cons first rest))
(my-list 1 2 3)

多 arity

defun 与 fn 接受多个子句:按实参数从上到下首匹配(精确子句匹配 argc=n,& rest 子句匹配 argc>=n);零匹配报条件 no-matching-arity。

(defun abs2
  ([x] (if (< x 0) (- x) x))
  ([x y] (max (abs2 x) (abs2 y))))
[(abs2 -5) (abs2 3 9)]
(defun greet
  ([name] (str "hi " name))
  ([name & titles] (str "hi " name " " (count titles))))
[(greet "Ada") (greet "Ada" :dr :prof)]

解构

let 与 fn 参数都支持向量模式与 map 模式(可嵌套):向量 [a b & rest :as all](rest 是 list、不足报错、多余丢弃);map {:keys [x y] :as m}(缺键绑 nil)。

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