简体   繁体   中英

Tail recursion in clojure

This is a lisp code that uses tail recursion.

(defun factorial (f n)
    (if (= n 1)
        f
        (factorial (* f n) (- n 1))))

I translate this into clojure code expecting the same tail recursion optimization.

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

However I got this integer overflow (not stack overflow) even with small number such as (fact 1 30) .

ArithmeticException integer overflow  clojure.lang.Numbers.throwIntOverflow (Numbers.java:1374)

I tried with recur , but got the same error.

(defn factorial [f n]
    (if (= n 1)
        f
        (recur (* f n) (dec n))))

What's wrong with the clojure code?

Nothing, just use BigInt s:

(factorial 1N 30N) ;=> 265252859812191058636308480000000N

The arguments may be small, but the result is not!

Note that ticked versions of the arithmetic operators are also available, which support arbitrary precision:

(reduce *' (range 1 31)) ;=> 265252859812191058636308480000000N

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM