How does this core.match binding example work?

78 views Asked by At

See this example:

(let [x 1 y 2]
  (match [x y]
    [1 b] b
    [a 2] a
   :else nil))
;=> 2

I can't get my head around a few things:

  1. Does 1 match x and gets bound to b?
  2. Does 2 match y and gets bound to a?
  3. Assuming I got the two points above right, why return a instead of b considering they both matched part of [x y]. Is it because it is the last clause?
1

There are 1 answers

1
Taylor Wood On BEST ANSWER

Think of each pattern as a template to be matched to the input [x y] or [1 2].

The first pattern is [1 b] which matches the input because the first template item is a matching literal value 1, and the second template item is a binding that will hold any value in that position of the input, which happens to be 2 in this case. That b binding is accessible from the righthand side of the match clause, as if it were a let binding.

This example might demonstrate it more clearly:

(let [x 1 y 2]
  (match [x y]
    [1 b] [1 (inc b)] ;; recreate the input with (inc b)
    [a 2] a           ;; this never matches because prior match works
    :else nil))
=> [1 3]

Does 2 match y and gets bound to a?

The pattern is a match, but it doesn't matter because the preceding pattern was already a match. If it were the successful match, a would be bound to 1.