Last active
November 12, 2015 06:37
-
-
Save fgui/8a44c2698cd0f0b76dd3 to your computer and use it in GitHub Desktop.
playing with recur (tail vs lazy-seq)
This file contains hidden or 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
(ns recur.mult-recur-example) | |
(defn mul-recur [a b] | |
(+ a (mul-recur a (dec b)))) | |
(defn mul-recur2 [a b] | |
(+ a (mul-recur a (dec b)))) | |
(defn mul-recur-tail [a b] | |
(loop [acc 0N left b] | |
(if (zero? left) acc | |
(recur (+ acc a) (dec left))))) | |
(defn mul-seq [a b] | |
((fn m [acc left] | |
(if (zero? left) (list acc) | |
(cons acc (m (+ acc a) (dec left))))) 0N b)) | |
(defn mul-seq-lazy [a b] | |
((fn m [acc left] | |
(if (zero? left) (list acc) | |
(lazy-seq (cons acc (m (+ acc a) (dec left)))))) 0N b)) | |
;; now lets transform the seq solutions to not ending sequence | |
(defn mul-of-a-number [a] | |
((fn m [acc] | |
(lazy-seq (cons acc (m (+ acc a))))) 0N)) | |
(defn mul-of-a-number-hof [a] | |
(iterate (fn [acc] (+ acc a)) 0N)) | |
(defn iterate-recur [f ini nth] | |
(loop [val ini left nth] | |
(if (zero? left) val | |
(recur (f val) (dec left)) | |
))) | |
(defn mul-of-a-number3 [a] | |
(partial iterate-recur (fn [acc] (+ acc a)) 0N)) | |
((mul-of-a-number3 3) 10) | |
(comment | |
(do | |
(def a 3) | |
(def big-n 1000000) | |
(time (mul-recur-tail a big-n)) | |
(time (first (drop big-n (mul-of-a-number a)))) | |
(time (first (drop big-n (mul-of-a-number-hof a)))) | |
) | |
) | |
(def fib (iterate (fn [n-1 n] [n (+ n-1 n)]))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment