Skip to content

Instantly share code, notes, and snippets.

@noahlz
Created July 2, 2012 21:59
Show Gist options
  • Save noahlz/3035990 to your computer and use it in GitHub Desktop.
Save noahlz/3035990 to your computer and use it in GitHub Desktop.
Factorial computation in clojure
(defn factorial-using-recur [x]
(loop [current x
next (dec current)
total 1]
(if (> current 1)
(recur next (dec next) (* total current))
total)))
(defn factorial-using-reduce [x]
(reduce * (range 1 (inc x))))
(defn make-fac-function [n]
(fn [] (reduce * (range 1 (inc n)))))
; produces a function that will calculate the factorial on demand
(defmacro factorial-using-macro [x]
`(fn [] (* ~@(range 1 (inc x)))))
;; (macroexpand `(factorial-using-macro 10))
;; => (fn* ([] (clojure.core/* 1 2 3 4 5 6 7 8 9 10)))
(defn factorial-using-cons-and-eval [x]
(eval (cons '* (range 1 (inc x)))))
(defn factorial-with-apply [x]
(apply * (range 1 (inc x))))
(assert (== (factorial-using-reduce 5)
((make-fac-function 5))
((factorial-using-macro 5))
(factorial-using-recur 5)
(factorial-using-cons-and-eval 5)
(factorial-with-apply 5)
(* 1 2 3 4 5))
"something broke")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment