Lazy Friends

Interestingly, take is itself lazy. It does indeed return the first N items of the sequence you pass to it, but it doesn’t actually grab anything off of the sequence until you ask for it. Thus this:

 (​def​ many-nums (take 1000000000 (iterate inc 1)))

doesn’t create a billion-item collection immediately. Instead take knows that it should limit itself to the first billion items, but like the lazy sod that it is, take waits to be asked before it does anything. So this:

 (println (take 20 (take 1000000000 (iterate inc 1))))

will print the first 20 integers and is only microscopically slower at doing so than the version sans the inner take.

take isn’t alone in being surprisingly lazy. A lot of the sequence functions that we’ve been ...

Get Getting 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.