Skip to the content
Diaspar

07 / 10

Patterns and match

One pattern language for match, let and parameters.

A pattern is the shape of a value, written the way the value is built. match takes a value and a list of clauses, a pattern and then a result, and gives the result of the first pattern that fits.

shapes.dias
(defn describe [x]
  (match x
    nil "nothing"
    0 "zero"
    "hello" "a greeting"
    :ready "the keyword :ready"
    #[] "an empty vector"
    #[a] f"one element: {a}"
    #[a b] f"a pair: {a} and {b}"
    #[a & more] f"{a}, then {(count more)} more"
    #{:name name} f"something named {name}"
    _ "something else"))

(defn main [args]
  (for [x #[nil 0 "hello" :ready #[] #[7] #[1 2] #[1 2 3 4]
            #{:name "Alvin" :age 20} 3.5]]
    (print (describe x))))
Runs in your browser

Try it: Add a clause for a vector of exactly three elements, above the one with & more. Then move it below, and see who wins.

  • A number, a string, a keyword or nil matches itself.
  • A lower-case name matches anything and becomes a name for it. _ matches anything and names nothing.
  • #[a b] matches a sequence of two. & more takes the rest, however many.
  • #{:name name} matches a map that has the key, whatever else it holds.

Clauses are tried from the top, so the narrow ones go first.

Tests, names and choices

A pattern says what shape a value has. Three labels say the rest. when: adds a test in ordinary code. as: names the whole value the pattern matched. And (or …) matches any of several patterns.

guards.dias
(deftype Ship [name seats])

(defn describe [x]
  (match x
    ;; when: adds a test to a pattern.
    n when: (and (number? n) (< n 0)) "a negative number"
    n when: (number? n) "a number"

    ;; A pattern inside a pattern, and a value where a name could be.
    (Ship seats: 1) "a ship for one"
    (Ship name: seats:) when: (> seats 100) f"{name}, a liner"

    ;; as: names the whole value that the pattern matched.
    (Ship) as: ship f"a ship: {ship}"

    ;; or matches any of several patterns.
    (or :yes :ok true) "agreement"
    _ "something else"))

(defn main [args]
  (for [x #[-5 42 (Ship name: "Skiff" seats: 1) (Ship name: "Ark" seats: 500)
            (Ship name: "Seeker" seats: 3) :ok "?"]]
    (print (describe x))))
Runs in your browser

Try it: Add a clause for a ship whose name is exactly "Seeker": (Ship name: "Seeker") "the Seeker herself". Put it where it will be reached.

(Ship seats: 1) has a value where a name could be: it matches only a ship with one seat. (Ship) with no fields matches any ship.

The same patterns everywhere

Wherever a value gets a name, a pattern can stand instead: in let, in for, and in a function's parameters. A function can also have several clauses, each with its own patterns, and the first that fits its arguments runs.

everywhere.dias
(deftype Ship [name seats])

;; A function may have several clauses, each with its own patterns.
(defn fib
  ([0] 0)
  ([1] 1)
  ([n] (+ (fib (- n 1)) (fib (- n 2)))))

;; A parameter is a pattern.
(defn room? [(Ship seats:) crew]
  (< (count crew) seats))

(defn main [args]
  (print (fib 20))
  (print (room? (Ship name: "Seeker" seats: 3) #["Alvin" "Hilvar"]))

  ;; So is the left side of a let, and of a for.
  (let [#[first-one & others] #["Alvin" "Hilvar" "Alystra"]
        #{port (host default: "localhost")} #{:port 8080}]
    (print first-one others)
    (print host port))
  (for [#[name seats] #[#["Seeker" 3] #["Ark" 500]]]
    (print name "seats" seats)))
Runs in your browser

Try it: Remove :port 8080 from the map in let. host has a default and port does not, and the report says how to give it one.

When nothing matches

A match with no clause for its value is an error, at the match, with the value that had nowhere to go.

none.dias
(defn name-of [n]
  (match n
    1 "one"
    2 "two"))

(defn main [args]
  (print (name-of 1))
  (print (name-of 3)))
Runs in your browser

Try it: Add a last clause, _ "many".

It never gives nil and carries on. For the variants of an enum you do not even have to run the program to find out: the page on enums shows the warning that names the missing one.