O'Reilly logo

Clojure Applied by Alex Miller, Ben Vandgrift

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Filtering and Removing Values

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required