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

Get Clojure Applied 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.