简体   繁体   English

如何将已定义的函数函数转换为匿名函数

[英]How to turn a defined function function into an anonymous one

I want to turn a defined function into an anonymous one. 我想将一个已定义的函数转换为匿名函数。 How do I do that? 我怎么做? The following function returns the last element from a sequence: 以下函数返回序列中的最后一个元素:

(defn lastt [l]
    (cond
        (nil? (next l)) l
        :else
            (lastt (next l))))

How do I turn it into fn form? 如何将其转换为fn格式?

PS: I know about last function, this is just an exercise. PS:我知道last功能,这只是一个练习。

First of all, that function returns a list with the last item in it. 首先,该函数返回一个列表,其中包含最后一项。 I'd change your definition so that it returns just the last item: 我会改变你的定义,使其返回最后一个项目:

(defn lastt [l]
  (cond
   (nil? (next l)) (first l)
   :else (lastt (next l))))

To simplify, I'd use a let binding since you're calling next twice on l : 为了简化,我会使用一个let约束力,因为你打电话next的两次l

(defn lastt [l]
  (let [n (next l)]
    (cond
     (nil? n) (first l)
     :else (lastt n))))

The next thing I'd do is replace the final call to lastt to use recur instead 我要做的下一件事就是将最后一次调用替换为lastt来代替使用recur

(defn lastt [l]
  (let [n (next l)]
    (cond
     (nil? n) (first l)
     :else (recur n))))

And then I'd replace that with 然后我会替换它

#(let [n (next %)]
   (cond
    (nil? n) (first %)
    :else (recur n)))

And just realised that it could be simplified even more using destructuring :) 并且意识到使用解构可以简化它:)

#(let [[h & t] %]
   (cond
    (nil? t) h
    :else (recur t)))

Updated 更新

No need for the cond , since there's only two branches, and using fn instead of the # shorthand will allow the destructuring to happen in the fn 's parameters, making the whole function a little bit more concise: 无需在cond ,因为这里只有两个分支,并且使用fn代替#速记将允许解构在发生fn的参数,使整机功能更加简洁一点:

(fn [[h & t]]
  (if (empty? t) h
      (recur t)))

I'm more of a schemer/CLer than a clojer, but (defn f [args] body) looks to be mostly syntactic sugar for (def f (fn f ([args] body))) , in which case lastt could be written as an anonymous function by leaving out the def : 我更像是一个策划者/克莱尔而不是一个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)))))

Since lastt recurses, you need to provide a name to bind it to within the body. lastt ,您需要提供一个名称以将其绑定到正文中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM