Staying Out of Trouble

The good news is that Clojure comes equipped with a large assortment of functions to do interesting things with sequences—so many that we can only scratch the surface in this chapter. There’s everything from butlast (give me all but the last element) to zipmap (build a map from two sequences). The bad news is that until you’re familiar with what’s available you’ll tend to reinvent the wheel. In particular, if you find yourself processing a sequence one item at a time, perhaps with loop and recur, like this:

 (​defn​ total-sales [books]
 "Total up book sales. Books maps must have :sales key."
  (loop [books books total 0]
  (​if​ (empty? books)
  total
  (recur (next books)
  (+ total (:sales (first books)))))))

consider ...

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.