Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this core.match binding example work?

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?
like image 863
customcommander Avatar asked Aug 09 '26 17:08

customcommander


1 Answers

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.

like image 134
Taylor Wood Avatar answered Aug 11 '26 10:08

Taylor Wood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!