Created
July 27, 2010 20:29
-
-
Save raek/492810 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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