Skip to content

Instantly share code, notes, and snippets.

@hindol
Created February 26, 2020 05:56
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save hindol/e6eba6bbc27289985ea7a5d242629d87 to your computer and use it in GitHub Desktop.
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]
(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