Multiple arities in Clojure
A watering function with a default arity, plus a variadic label builder.
(require '[clojure.string :as str])
;; two arities: the short one fills in a default and calls the long one
(defn water
([bed] (water bed 2))
([bed liters]
(str "watering " bed " with " liters "L")))
(println (water "tomatoes"))
(println (water "ferns" 5))
;; & gathers the leftover arguments into a seq, or nil when there are none
(defn label [bed & remarks]
(str bed (when (seq remarks)
(str " - " (str/join "; " remarks)))))
(println (label "beans"))
(println (label "beans" "shade cloth" "sow again in June"))
How it works
([bed] (water bed 2))fills in a default and calls the two-argument arity.- The longer arity takes
[bed liters]and formats the message withstr. [bed & remarks]gathers leftover arguments into a seq that(seq remarks)checks before joining.
Keywords and builtins used here
defnlabelprintlnrequireseqstrwaterwhen
The run, in numbers
- Lines
- 18
- Characters to type
- 517
- Tokens
- 99
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 79 seconds.
Step 3 of 3 in Functions, step 9 of 27 in Language basics.