我想将定义的函数变成匿名函数。我怎么做?以下函数返回序列中的最后一个元素:
(defn lastt [l]
(cond
(nil? (next l)) l
:else
(lastt (next l))))
我如何把它变成fn形式?
PS:我知道last函数,这只是一个练习。
我想将定义的函数变成匿名函数。我怎么做?以下函数返回序列中的最后一个元素:
(defn lastt [l]
(cond
(nil? (next l)) l
:else
(lastt (next l))))
我如何把它变成fn形式?
PS:我知道last函数,这只是一个练习。
首先,该函数返回一个列表,其中包含最后一项。我会更改您的定义,使其仅返回最后一项:
(defn lastt [l]
(cond
(nil? (next l)) (first l)
:else (lastt (next l))))
为简化起见,我会使用let绑定,因为您要调用next两次l:
(defn lastt [l]
(let [n (next l)]
(cond
(nil? n) (first l)
:else (lastt n))))
我要做的下一件事是替换最后的调用来lastt使用recur
(defn lastt [l]
(let [n (next l)]
(cond
(nil? n) (first l)
:else (recur n))))
然后我会用
#(let [n (next %)]
(cond
(nil? n) (first %)
:else (recur n)))
并且刚刚意识到使用解构可以进一步简化它:)
#(let [[h & t] %]
(cond
(nil? t) h
:else (recur t)))
更新
不需要cond,因为只有两个分支,使用fn而不是#速记将允许在fn的参数中进行解构,使整个函数更加简洁:
(fn [[h & t]]
(if (empty? t) h
(recur t)))
我更像是一个计划者/CLer而不是一个clojer,但(defn f [args] body)看起来主要是语法糖(def f (fn f ([args] body))),在这种情况下lastt可以通过省略def:
(fn lastt
([l] (cond
(nil? (next l))
l
:else
(lastt (next l)))))
由于lastt递归,您需要提供一个名称以将其绑定到正文中。