Deeply Recursive

Along with letting you do interesting things with your function arguments, Clojure also provides specialized support for writing recursive functions. A recursive function is, of course, a function that calls itself. For example, suppose we had this collection of book maps:

 (​def​ books
  [{:title ​"Jaws"​ :copies-sold 2000000}
  {:title ​"Emma"​ :copies-sold 3000000}
  {:title ​"2001"​ :copies-sold 4000000}])

and we wanted to know the total number of books sold. We could write a recursive function to run through all the elements of the vector:

 (​defn​ sum-copies
  ([books] (sum-copies books 0))
  ([books total]
  (​if​ (empty? books)
  total
  (sum-copies
  (rest books)
  (+ total (:copies-sold (first books)))))))

Notice ...

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.