Clojure 中的非尾递归匿名函数
如何在 Clojure 中创建非尾递归的递归匿名函数?
以下显然不起作用,因为 recur
仅适用于尾递归函数。我也不愿意拖入 y 组合器..
((fn [n] (if (= 1 n) 1 (* n (recur (dec n))))) 5)
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 reluctant to drag in a y-combinator..
((fn [n] (if (= 1 n) 1 (* n (recur (dec n))))) 5)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以通过在
fn
和 arglist 之间指定函数来给函数指定一个名称来引用自身:Functions can be given a name to refer to themselves by specifying it between
fn
and the arglist:这是一种保持匿名的方法,主要是:
它不完全是 Y 组合器,但它确实包含相同的自我应用程序,允许 Y 做它的事情。只要您需要,只要在
!
范围内复制整个函数,您就可以随时制作另一个副本。Here's a way that keeps it anonymous, mostly:
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.