May 2018
Beginner to intermediate
290 pages
6h 43m
English
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 ...
Read now
Unlock full access