Skip to content

Instantly share code, notes, and snippets.

Created Feb 26, 2020
What would you like to do?
Clojure Lazy Sequences Explained
;; 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]
(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