typestar

Varargs and option maps in Clojure

Sums any number of arguments, spreads a vector back into them, and pads a label from an options map.

;; & collects any trailing arguments into a sequence, so one defn
;; accepts as many as the caller cares to pass.
(defn total [& amounts] (reduce + 0 amounts))
(println (total 5 10 15))

;; apply spreads a collection back out into those argument slots.
(def readings [12 7 19 4])
(println (apply total readings))

;; An options map keeps settings named instead of positional;
;; destructure it with :keys and fill the gaps with :or.
(defn pad-label
  [text & {:keys [width fill] :or {width 12 fill \.}}]
  (apply str text (repeat (max 0 (- width (count text))) fill)))

(println (pad-label "cotton"))
(println (pad-label "cotton" :width 20 :fill \-))

How it works

  1. (defn total [& amounts] (reduce + 0 amounts)) gathers every trailing argument into one sequence.
  2. (apply total readings) feeds the elements of readings in as separate positional arguments.
  3. pad-label accepts & {:keys [width fill] :or {width 12 fill \.}}, so a caller passes :width 20 by name.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
646
Tokens
107
Three-star pace
70 tpm

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

Type this snippet

Step 3 of 3 in Destructuring, step 21 of 27 in Language basics.

← Previous Next →