A Lazy Sequence

Some factorial refactorings

A pointless collection of factorial implementations in Clojure.

1
2
3
4
5
6
(defn fac1 
    "Basic recursive factorial"
    [n]
    (if (= n 1) 
        1 
        (* n (fac1 (dec n)))))

1
2
3
4
5
6
7
8
(defn fac2
    "Recursive factorial with loop/recur"
    [n]
    (loop [i n
           total 1]
        (if (= i 1)
            total
            (recur (- i 1) (* total i)))))

1
2
3
(defmulti fac3 identity)
(defmethod fac3 1 [_] 1)
(defmethod fac3 :default [n] (* n (fac3 (dec n))))

1
2
3
4
(defn fac4
    [n]
    "Factorial as an implicit hylomorphism" 
    (reduce * (range 1 (inc n))))

1
2
3
(defn fac5 
    [n]
    (apply * (take n (iterate inc 1))))

8 October 2009