Programming-Idioms

History of Idiom 31 > diff from v41 to v42

Edit summary for version 42 :
[Clojure] formatting and docs

Version 41

2017-12-21, 03:00:11

Version 42

2017-12-21, 03:16:17

Idiom #31 Recursive factorial (simple)

Create recursive function f which returns the factorial of non-negative integer i, calculated from f(i-1)

Idiom #31 Recursive factorial (simple)

Create recursive function f which returns the factorial of non-negative integer i, calculated from f(i-1)

Code
(defn f [i]
  (loop [i i acc 1N]
    (if (zero? i)
      acc
      (recur (dec i) (* i acc)))))
Code
(defn f [i]
  (loop [cnt i, acc 1N]
    (if (zero? cnt)
      acc
      (recur (dec cnt) (* cnt acc)))))
Comments bubble
This supports arbitrary-precision.
Replace 1N (clojure.lang.BigInt) with 1 (java.lang.Long) if you don't need to calculate anything above (f 20).
Comments bubble
This supports arbitrary-precision and self tail call optimization.
Doc URL
https://clojuredocs.org/clojure.core/recur#example-542692d0c026201cdc326ea6
Origin
https://clojuredocs.org/clojure.core/recur#example-542692d0c026201cdc326ea6
Demo URL
https://repl.it/repls/SerpentineFunnyYnambu
Demo URL
https://ideone.com/wk8obN