简体   繁体   English

Clojure中记录的模式匹配

[英]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: 我能找到的唯一信息是维基( https://github.com/clojure/core.match/wiki/Deftype-and-defrecord-matching )中的示例,它会产生错误:

CompilerException java.lang.AssertionError: Invalid list syntax (Red. (Red. axb) yc) in (Black. (Red. (Red. axb) yc) zd). CompilerException java.lang.AssertionError:无效的列表语法(Red。(Red.axb)yc)in(Black。(Red。(Red.axb)yc)zd)。 Valid syntax: [[:default :guard] [:or :default] [:default :only] [:default :seq] [:default :when] [:default :as] [:default :<<] [:default :clojure.core.match/vector]] 有效语法:[[:default:guard] [:或:default] [:default:only] [:default:seq] [:default:when] [:default:as] [:default:<<] [:default :clojure.core.match /载体]]

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 https://github.com/clojure/core.match/wiki/Basic-usage#map-patterns

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM