Clojure Programming/Examples/API Examples/Mapping Operators

From Wikibooks, open books for an open world
Jump to: navigation, search

map[edit]

user=> (map + [1 2 3 4] [1 2 3 4])
(2 4 6 8)

reduce[edit]

user=> (reduce * [2 3 4])
24
; sum the odd numbers to 100
;; Not so beautiful code, see next example for a better approach
(reduce #(+ %1 (if (= 1 (rem %2 2)) %2 0)) (range 100)) 

; sum the odd numbers to 100 (Cleaner version)
(reduce + (filter odd? (range 100)))

apply[edit]

user=> (apply str [1 2])
"12"

(defn factorial [n] 
  (apply * (range 2 (inc n))))