August 2015
Intermediate to advanced
220 pages
5h 53m
English
Instead of being passed a collection of planets, we might be passed a collection of all entities in the solar system. In that case, to compute the total number of moons, we need to filter down to only the planets, then extract the moon count, and sum the moons. Let’s see how this looks first with sequences:
| cljapplied/src/ch3/orbital.clj | |
| | (defn planet? |
| | [entity] |
| | (instance? Planet entity)) |
| | |
| | (defn total-moons |
| | [entities] |
| | (reduce + 0 |
| | (map :moons |
| | (filter planet? |
| | entities)))) |
We’ve defined a planet? helper function that tests whether an entity is a Planet. In Clojure, functions that return a truthy value are are referred to as predicates. They’re often given names that end with ?. Typically ...
Read now
Unlock full access