Created
February 26, 2020 05:56
-
-
Save hindol/e6eba6bbc27289985ea7a5d242629d87 to your computer and use it in GitHub Desktop.
Clojure Lazy Sequences Explained
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
;; Let's say, we want a sequence of all the powers of a number. | |
(defn powers | |
([x] (powers x x)) | |
([x p] | |
(cons p (powers x (* x p))))) | |
(powers 2) | |
;; => integer overflow | |
;; This throws an error because we cannot really calculate an infinite sequence. | |
;; Let's try to read only the first two elements. | |
(take 2 (powers 2)) | |
;; => integer overflow | |
;; This still throws because before returning the first two elements, | |
;; it is still trying to calculate the whole sequence! | |
;; Let's make this lazy. | |
(defn powers | |
([x] (powers x x)) | |
([x p] | |
(lazy-seq | |
(cons p (powers x (* x p)))))) | |
(take 2 (powers 2)) | |
;; => (2 4) | |
;; Notice that we have only added lazy-seq in a strategic place. | |
;; What this actually does is it delays the evaluation of the thing | |
;; wrapped in lazy-seq till it's actually requested. So, if we | |
;; request two elements, only the first two cells of the logically | |
;; infinite sequence is evaluated. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment