Skip to content

Instantly share code, notes, and snippets.

@raek
Created July 27, 2010 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raek/492810 to your computer and use it in GitHub Desktop.
Save raek/492810 to your computer and use it in GitHub Desktop.
;; Eats stack, don't do this
(defn fac-naive [n]
(if (zero? n)
1
(* n (fac-naive (dec n)))))
;; Uses a helper function to get an extra parameter when recurring
(defn fac-recur-hepler [n]
(letfn [(fac-helper [n acc]
(if (zero? n)
acc
(recur (dec n) (* n acc))))]
(fac-helper n 1)))
;; Uses loop to get an extra parameter when recurring
(defn fac-recur-loop [n]
(loop [n n, acc 1]
(if (zero? n)
acc
(recur (dec n) (* n acc)))))
;; Finite lazy seqeunce of the factorials of 0, 1, 2, 3, ..., n
(defn finite-fac-seq [n]
(letfn [(fac-step [i acc]
(lazy-seq
(if (= i (inc n))
nil
(cons acc (fac-step (inc i) (* (inc i) acc))))))]
(fac-step 0 1)))
(defn fac-from-finite-seq [n]
(nth (finite-fac-seq n) n))
;; Infinite lazy sequence of the facortials of 0, 1, 2, 3, ...
(defn infinite-fac-seq []
(letfn [(fac-step [i acc]
(lazy-seq
(cons acc (fac-step (inc i) (* (inc i) acc)))))]
(fac-step 0 1)))
(defn fac-from-infinite-seq [n]
(nth (infinite-fac-seq) n))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment