自动TCO Clojure中 [英] Automatic TCO in Clojure

查看:133
本文介绍了自动TCO Clojure中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法Clojure中定义一个函数,自动尾调用优化?

Is there a way to define a function in Clojure that is automatically tail-call-optimized?

例如

(defrecur fact [x]
    (if (= x 1)
        1
        (* x (fact (dec x)))))

将被内部转换为类似于:

would be translated internally to something like:

(defn fact [x]
    (loop [n x f 1]
        (if (= n 1)
            f
            (recur (dec n) (* f n)))))

你能告诉我,如果这样的事情已经存在?

Can you tell me if something like this already exists?

推荐答案

简短的回答是否。

稍长的答案是,Clojure是故意设计要求,其中尾调用优化需要明确的指示,因为JVM不支持它本身。

The slightly longer answer is that Clojure is deliberately designed to require explicit indication where Tail Call Optimisation is desired, because the JVM doesn't support it natively.

顺便说一句,你可以使用复发没有循环,所以没有需要更多的输入,如:

Incidentally, you can use recur without loop, so there's no more typing required, e.g.:

(defn func [x]
  (if (= x 1000000)
    x
    (recur (inc x))))

更新后,4月29日:

克里斯Frisz一直在 Clojure的TCO 研究项目与丹·弗里德曼,以及虽然没有人声称它是在这个时候的答案,该项目是既有趣和有希望的。克里斯最近发表了一个非正式的谈这个项目,并他张贴在他的博客

Chris Frisz has been working on a Clojure TCO research project with Dan Friedman, and whilst nobody is claiming it to be 'the answer' at this time, the project is both interesting and promising. Chris recently gave an informal talk about this project, and he's posted it on his blog.

这篇关于自动TCO Clojure中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆