Pattern 18Lazy Sequence

Intent

To create a sequence whose members are computed only when needed—this allows us to easily stream results from a computation and to work with infinitely long sequences

Overview

We often deal with elements of a sequence one at a time. Since this is so, we generally don’t need to have the entire sequence realized before we start processing it. For instance, we may wish to stream lines of a file off of disk and process them without ever holding the entire file in memory. We could use Pattern 12, Tail Recursion, to seek through the file, but Lazy Sequence provides a much cleaner abstraction for this sort of streaming computation.

Lazy Sequence does so by only creating an element in a sequence when it’s asked for. ...

Get Functional Programming Patterns in Scala and Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.