开发者

Non tail-recursive anonymous functions in Clojure

开发者 https://www.devze.com 2023-02-23 13:15 出处:网络
How do I create a recursive anonymous function in Clojure which is not tail recursive? The following clearly doesn\'t work, as recur is only for tail recursive functions.I\'m also reluct开发者_Go百科

How do I create a recursive anonymous function in Clojure which is not tail recursive?

The following clearly doesn't work, as recur is only for tail recursive functions. I'm also reluct开发者_Go百科ant to drag in a y-combinator..

((fn [n] (if (= 1 n) 1 (* n (recur (dec n))))) 5)


Functions can be given a name to refer to themselves by specifying it between fn and the arglist:

user> ((fn ! [n] (if (= 1 n) 1 (* n (! (dec n))))) 5)
120


Here's a way that keeps it anonymous, mostly:

(((fn [!] (fn [n] (if (= 1 n) 1 (* n ((! !) (dec n)))))) 
  (fn [!] (fn [n] (if (= 1 n) 1 (* n ((! !) (dec n))))))) 
 5)

It's not quite the Y combinator, but it does contain the same bit of self-application that allows Y to do its thing. By having a copy of the entire function in scope as ! whenever you need it, you can always make another copy.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号