Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching on records in Clojure

Is this supported right now? The only information I could find was the example from the wiki (https://github.com/clojure/core.match/wiki/Deftype-and-defrecord-matching) which produces an error:

CompilerException java.lang.AssertionError: Invalid list syntax (Red. (Red. a x b) y c) in (Black. (Red. (Red. a x b) y c) z d). Valid syntax: [[:default :guard] [:or :default] [:default :only] [:default :seq] [:default :when] [:default :as] [:default :<<] [:default :clojure.core.match/vector]]

like image 612
estolua Avatar asked Nov 01 '22 07:11

estolua


1 Answers

This has not been implemented yet, but since records behave as maps you can do:

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

You can also match on the type of the record, but it is a bit inelegant.

user> (let [x (->ab 1 1)
            aba user.ab]
  (match [(type x) x]
    [aba {:a _ :b 2}] :a0
    [aba {:a 1 :b 1}] :a1
    [aba {:c 3 :d _ :e 4}] :a2
    :else nil))
  :a1

https://github.com/clojure/core.match/wiki/Basic-usage#map-patterns

like image 169
mac Avatar answered Nov 17 '22 21:11

mac