是什么名字?” 在Clojure的fn中争论?

Pet*_*son 3 clojure

我正在阅读拉斯·奥尔森(Russ Olsen)的著作《 Getting Clojure》。在第8章“ Def,Symbol和Vars”中,有以下函数定义:

(def second (fn second [x] (first (next x))))
                ^^^^^^
Run Code Online (Sandbox Code Playgroud)

我的问题是关于带下划线的second,它是第二位的。

起初,我认为这种语法是错误的,因为匿名函数不需要名称。但事实证明,这种语法是正确的。

Usage: (fn name? [params*] exprs*)
       (fn name? ([params*] exprs*) +)
Run Code Online (Sandbox Code Playgroud)

我尝试比较以下两个函数调用。

user> (fn second [x] (first (rest x)))
#function[user/eval5642/second--5643]
user> (fn [x] (first (rest x)))
#function[user/eval5646/fn-5647]
Run Code Online (Sandbox Code Playgroud)

除了函数的名称外,似乎没有什么区别。

为什么会有name?争论fn

Lee*_*Lee 5

您可以在创建多个Arity时使用它:

(fn second
      ([x] (second x 1))
      ([x y] (+ x y)))
Run Code Online (Sandbox Code Playgroud)

或者如果您需要进行递归调用:

(fn second [x] (when (pos? x)
                  (println x)
                  (second (dec x))))
Run Code Online (Sandbox Code Playgroud)