Automatic TCO in Clojure

偶尔善良 提交于 2019-12-13 18:34:13

问题


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

e.g.

(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?


回答1:


The short answer is "No".

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))))

Update, April 29:

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.




回答2:


To the best of my knowledge, there is no automatic way to generate tail recursion in Clojure.

There are examples of functions that use recursion without using loop .. recur that work without overflowing the stack. That is because those functions have been carefully written to use lazy sequences.

Here is an example of replacing flatten with a hand-written function. This example came from http://yyhh.org/blog/2011/05/my-solutions-first-50-problems-4clojure-com

(fn flt [coll]
  (let [l (first coll) r (next coll)]
    (concat 
      (if (sequential? l)
        (flt l)
        [l])
      (when (sequential? r)
        (flt r)))))



回答3:


One of the guiding principals behind this decision was to make the special part look special. that way it is obvious where tail calls are in use and where they are not. This was a deliberate design decision on which some people have strong opinions though in practice I rarely see recur used in idomatic Clojure anyway so In practice it's not a common problem.



来源:https://stackoverflow.com/questions/10212928/automatic-tco-in-clojure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!