Last active
December 14, 2015 11:59
-
-
Save senior/5083576 to your computer and use it in GitHub Desktop.
lazy-dog
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
| (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