Last active
August 29, 2015 14:07
-
-
Save erkiesken/f498f5b943a40d71ea04 to your computer and use it in GitHub Desktop.
Example of Mori lazy_seq
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
In Clojure (from Clojur Programming book, p94): | |
(defn random-ints | |
"Returns a lazy seq of random integers in the range [0,limit)." | |
[limit] | |
(lazy-seq | |
(cons (rand-int limit) | |
(random-ints limit)))) | |
(take 10 (random-ints 50)) | |
;= (32 37 8 2 22 41 19 27 34 27) | |
In JavaScript with Mori: | |
function randomInts (limit) { | |
return M.lazy_seq(function () { | |
return M.cons( | |
Math.random() * limit | 0, | |
randomInts(limit) | |
); | |
}); | |
} | |
M.take(10, randomInts(50)).inspect() | |
> "(37 44 27 14 34 43 13 0 36 37)" | |
-------------------- | |
And simplified with repeatedly, Clojure: | |
(repeatedly 10 (partial rand-int 50)) | |
Versus JavaScript + Mori: | |
randomLimit = function (limit) { return Math.random() * limit | 0; }; | |
M.repeatedly(10, M.partial(randomLimit, 50)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment