Commits

tednaleid committed 724eb84

my iterate

Comments (0)

Files changed (1)

src/four_clojure/answered.clj

 (ns four-clojure.answered)
 
+;; Listing uf 4clojure.com problems as I work through them
+;; My first working answer is the one that I leave uncommented in the code below, 
+;; definitely not always the best answer possible.
+;;
+;; After I've answered, I look at the other answers that some other people have given, I'll optionally add 
+;; a comment with some other interesting answers that people have given.
+
 ; from: http://stackoverflow.com/questions/2352020/debugging-in-clojure
 (defmacro dbg[x] `(let [x# ~x] (println "dbg:" '~x "=" x#) x#))
 (+ 4 (dbg (+ 3 6))) ; prints: dbg: (+ 3 6) = 9
 (= (gcd 1023 858) 33)
 
 
+; http://www.4clojure.com/problem/62
+; Re-implement Iterate
+; Given a side-effect free function f and an initial value x write a function which returns an infinite lazy sequence of x, (f x), (f (f x)), (f (f (f x))), etc.
+; restrictions: iterate
+
+(defn my-iterate [f x]
+  (cons x (lazy-seq (my-iterate f (f x)))))
+
+(= (take 5 (my-iterate #(* 2 %) 1)) [1 2 4 8 16])
+(= (take 100 (my-iterate inc 0)) (take 100 (range)))
+(= (take 9 (my-iterate #(inc (mod % 3)) 1)) (take 9 (cycle [1 2 3])))
+
+
 ; http://www.4clojure.com/problem/
 ;
 ;
 ;
 ;
 
-; http://www.4clojure.com/problem/
-;
-;
-