Factorial: Difference between revisions
Content deleted Content added
m →{{header|Clojure}}: Add more implementations |
|||
Line 338:
=={{header|Clojure}}==
'''Factorial as a folding (reduction) computation'''
<lang clojure>
(defn factorial [x]
(apply * (range 2 (inc x)))
)
</lang>
Or, in more idiomatical functional style:
<lang clojure>
(defn factorial [x]
(reduce * (range 2 (inc x)))
)
'''Recursion'''
<lang clojure>
(defn factorial [x]
(if (= x 0)
1
(* x (factorial (dec x)))))
</lang>
'''Tail recursion'''
<lang clojure>
(defn factorial [x]
(loop [x x
acc 1]
(if (<= x 1)
acc
(recur (dec x) (* acc x)))))
</lang>
|