Skip to content

Instantly share code, notes, and snippets.

@senior
Last active December 14, 2015 11:59
Show Gist options
  • Select an option

  • Save senior/5083576 to your computer and use it in GitHub Desktop.

Select an option

Save senior/5083576 to your computer and use it in GitHub Desktop.
lazy-dog
(defn lazy-dog
"Like concat or lazy-cat but does not realize the outer seq"
[coll]
(concat
(first coll)
(lazy-seq
(when-let [more (next coll)]
(lazy-dog more)))))
(defn make-lazy-seq [end]
(concat [[1 2 3]
[4 5 6]
[7 8 9]
[10 11 12]]
(lazy-seq
(do
(reset! end true)
nil))))
(deftest test-lazy-dog
(let [thing [[1 2 3]
[4 5 6]
[7 8 9]
[10 11 12]]]
(is (= (range 1 13)
(lazy-dog thing))))
;; lazy-dog does not realize the outer seq
(testing "Basic seq"
(let [end (atom false)]
(is (= (range 1 11)
(take 10 (lazy-dog (make-lazy-seq end)))))
(is (false? @end))))
;; mapcat realizes the outer seq
(testing "Comparison with mapcat"
(let [end (atom false)]
(is (= (range 1 11)
(take 10 (mapcat identity (make-lazy-seq end)))))
(is (true? @end))))
;; apply concat will realize the outter seq
(testing "Comparison with apply concat"
(let [end (atom false)]
(is (= (range 1 11)
(take 10 (apply concat (make-lazy-seq end)))))
(is (true? @end)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment