liveBook · Manning

Multiple arity

As explained in Clojure: The Essential Reference

Multiple arity is a function feature that provides distinct parameter lists and bodies for different argument counts.

Multiple arity lets one Clojure function accept different argument counts. In a `defn` with multiple arities, each parenthesized clause has its own parameter vector and body. section 2.1.1

Two ways to greet

(defn greet ([name] (str "Hello " name)) ([greeting name] (str greeting " " name))) (greet "Ada") ; => "Hello Ada" (greet "Welcome" "Ada") ; => "Welcome Ada" section 2.1.1

Use separate clauses when each argument count needs a distinct parameter list or body. A single-arity `defn` can use one parameter vector and body without wrapping them in a clause. section 2.1.1

How Clojure: The Essential Reference covers it

How deep it goes
Defines the declaration shape through parameter-vector/body pairs, but does not work through a multi-arity runtime example.
Examples
Uses a single-arity greeting and a declaration grammar showing repeated arity clauses.
What it assumes
Starts with a simple single-arity `defn` before introducing the form for multiple clauses.
What you can do after
Build it from scratch with `defn` by writing a parameter-vector/body clause for each supported argument count.
How it connects
Connects function arity to `defn`, `fn`, and parameter vectors.

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.