我在 Clojure 中定义了以下函数。
; return the input unchanged
(defn same [x] x)
; Recursively call the function on the input N times
(defn recurse-n-times [input function n]
(if (= n 0)
input
(recurse-n-times (function input) function (- n 1))
)
)
以下是我的递归函数的一些输出:
(recurse-n-times 0 inc 5) ; returns 5, as expected
(recurse-n-times 0 same 5) ; returns 0, as expected
(recurse-n-times 0 same 5000) ; StackOverflowError:
; clojure.lang.Numbers$LongOps.combine
; (Numbers.java:394)
我不明白为什么我得到一个StackOverflowError
. 最后一件事recurse-n-times
是调用自身,所以我希望它使用尾递归并且根本不增加堆栈。
我希望这个替代定义给出StackOverflowError
:
(defn bad-recurse-n-times [input function n]
(if (= n 0)
input
(function (alt-recurse-n-times input function (- n 1)))
)
)
为什么不recurse-n-times
使用尾递归?