I have defined the following functions in 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)) ) )
Here are some of the results of my recursive function:
(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)
I do not understand why I received a StackOverflowError
. The last thing recurse-n-times
does is call, so I expect it to use tail recursion and not expand the stack at all.
I will expect this alternative definition to give a StackOverflowError
:
(defn bad-recurse-n-times [input function n] (if (= n 0) input (function (alt-recurse-n-times input function (- n 1))) ) )
Why recurse-n-times
n't recurse-n-times
use tail recursion?
source share