Anonymous functions in Clojure
Passes unnamed functions to map and filter over a week of rainfall readings.
(def rainfall-mm [4 0 12 7 0 21])
;; fn makes a function with no name, used right where it is written
(println (map (fn [mm] (/ mm 10.0)) rainfall-mm))
;; #(...) is reader shorthand for the same thing, and % is the argument
(println (filter #(pos? %) rainfall-mm))
;; %1 and %2 name the arguments when there is more than one
(def notes (map #(str %1 " mm on day " %2) rainfall-mm (range 1 7)))
(println (first notes) "/" (last notes))
;; give the shorthand a name once the body starts earning one
(def wet-day? #(>= % 10))
(println "wet days:" (count (filter wet-day? rainfall-mm)))
How it works
(fn [mm] (/ mm 10.0))converts each reading to centimeters insidemap.#(pos? %)is the reader shorthand for the same idea, with%standing in for the argument.#(str %1 " mm on day " %2)names two arguments, andwet-day?shows the shorthand once it earns a name.
Keywords and builtins used here
countdeffilterfirstfnlastmapprintlnrangestr
The run, in numbers
- Lines
- 15
- Characters to type
- 586
- Tokens
- 100
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 86 seconds.
Step 2 of 3 in Functions, step 8 of 27 in Language basics.