Skip to content
map, filter, reduce
step 1/5

Reading — step 1 of 5

Learn

~1 min readCollections

The trinity of functional collection processing.

map — apply a function to each element:

(map inc [1 2 3])           ; (2 3 4)
(map #(* % %) [1 2 3])      ; (1 4 9)
(map + [1 2 3] [10 20 30])  ; (11 22 33)  -- multi-arg map

filter — keep elements where predicate is truthy:

(filter even? [1 2 3 4 5])  ; (2 4)
(filter #(> % 2) [1 2 3 4]) ; (3 4)

reduce — fold a collection to a single value:

(reduce + [1 2 3 4 5])      ; 15
(reduce + 100 [1 2 3])      ; 106  (with initial value)
(reduce max [3 1 4 1 5])    ; 5

Threading macros -> and ->> make pipelines readable:

(->> [1 2 3 4 5]
     (filter even?)
     (map #(* % %))
     (reduce +))                ; 20

->> threads the previous result as the LAST argument. -> threads as the FIRST argument. Use ->> for collection ops, -> for object/map ops.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…