Search code examples
clojurecore.match

in clojure, why core.match a map inside a vector?


from the sample code of core.match, url:https://github.com/clojure/core.match/wiki/Basic-usage

(let [x {:a 1 :b 1}]
  (match [x]
    [{:a _ :b 2}] :a0
    [{:a 1 :b 1}] :a1
    [{:c 3 :d _ :e 4}] :a2
    :else nil))

;=> :a1

why we can just match a `x' ? any reason why we can't do that ?

(let [x {:a 1 :b 1}]
  (match x
    {:a _ :b 2} :a0
    {:a 1 :b 1} :a1
    {:c 3 :d _ :e 4} :a2
    :else nil))

;=> :a1

Solution

  • You can; or at least that's what I'm inferring from reading the source and documentation of match.

    The source of match starts with the lines:

    (defmacro match
      . . .
      [vars & clauses]
      (let [[vars clauses]
            (if (vector? vars)  ; If it's a vector...
              [vars clauses]    ;  leave it alone,
              [(vector vars)    ;  else wrap it in a vector
                . . .]
    

    The documentation also contains the bit:

    . . . Optionally may take a single var not wrapped in a vector, questions then need not be wrapped in a vector.

    So why are they showing examples with vectors? Likely for consistency of the syntax. That likely help comprehension in a simple, basic overview like that. Switching back and forth between using and not using a vector would necessitate explaining when a vector is necessary, and that would detract from the main point of the page.


    Edit: Actually, it does explicitly explain on that page at the top that you can match on an unwrapped value. You can find it by searching for match x on that page.