O'Reilly logo

Clojure Applied by Alex Miller, Ben Vandgrift

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Take and Drop

Instead of building a subset of the collection based on a predicate, it’s often useful to take or remove the beginning of a collection. In Clojure the take and drop functions can accomplish this. For example, if we receive a sequence of solar system entities from an external source, we can retrieve the nth page of results with a function like this:

cljapplied/src/ch3/fn.clj
 
(​defn​ nth-page
 
"Return up to page-size results for the nth (0-based) page
 
of source."
 
[source page-size page]
 
(​->>​ source
 
(​drop​ (​*​ page page-size))
 
(​take​ page-size)))

This function first drops the number of pages up to the requested page, then takes the requested set of pages. The function uses sequences and doesn’t realize elements ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required