typestar

map & filter in Clojure

Bird sighting counts run through map, filter and mapv.

;; map applies a function to every element and returns a lazy seq
(def counts [3 12 7 20 5])
(println (map #(* 2 %) counts))

;; filter keeps the elements a predicate says yes to
(println (filter #(> % 6) counts))

(def sightings
  [{:species "junco" :count 12 :banded? true}
   {:species "siskin" :count 3 :banded? false}
   {:species "towhee" :count 20 :banded? true}])

;; a keyword is a function of a map, so it works as the mapped fn
(println (map :species sightings))

;; mapv is eager and hands back a vector instead of a lazy seq
(def flock-sizes (mapv :count sightings))
(println flock-sizes (map :species (filter :banded? sightings)))

How it works

  1. (map #(* 2 %) counts) applies a function to every element and returns a lazy seq.
  2. (filter #(> % 6) counts) keeps only the elements the predicate accepts.
  3. (map :species sightings) uses a keyword as the mapped function, and mapv hands flock-sizes back as a vector.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
636
Tokens
101
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 87 seconds.

Type this snippet

Step 1 of 3 in Sequences, step 13 of 27 in Language basics.

← Previous Next →

map & filter in other languages