typestar

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

  1. ([bed] (water bed 2)) fills in a default and calls the two-argument arity.
  2. The longer arity takes [bed liters] and formats the message with str.
  3. [bed & remarks] gathers leftover arguments into a seq that (seq remarks) checks before joining.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Functions, step 9 of 27 in Language basics.

← Previous Next →