【问题标题】:Combining s/and with s/or in Clojure spec在 Clojure 规范中结合 s/and 与 s/or
【发布时间】:2019-11-11 07:43:08
【问题描述】:

我想为具有键 :rule/children 或具有两个键 - :condition/field:condition/predicate 的映射编写规范。这是我尝试过的:

(s/keys :req [(s/or :children :rule/children :condition (s/and :condition/field :condition/predicate))])

它会导致错误消息:

Caused by: java.lang.AssertionError: Assert failed: all keys must be namespace-qualified keywords
(every? (fn* [p1__1917#] (c/and (keyword? p1__1917#) (namespace p1__1917#))) (concat req-keys req-un-specs opt opt-un))

我知道对于s/or,每个路径都必须命名。这里有两条路径 - 此地图可以有 :children:condition。只有具有:condition/field:condition/predicate 两个键时,它才是一个条件。

【问题讨论】:

    标签: clojure clojure.spec


    【解决方案1】:

    keys 规范中,您可以使用普通的orand 来执行此操作:

    (s/def ::map-spec
      (s/keys :req [(or :rule/children (and :condition/field :condition/predicate))]))
    
    (s/conform ::map-spec {:rule/children 1}) ;; valid
    (s/conform ::map-spec {:condition/field 1}) ;; invalid
    (s/conform ::map-spec {:condition/field 1 :condition/predicate 2}) ;; valid
    

    【讨论】:

    • 这里只是验证地图中关键字的存在。如果这些关键字本身具有与它们相关的规范,那么大概简单的orand 是不够的。对于这种情况,我将尝试使用 s/ors/and。我能感觉到另一个 SO 问题正在出现......
    • 实际上,orand 都可以,即使将关键字转换为适当的规范关键字,例如:condition/fieldi.am.a.spec.condition/field.
    猜你喜欢
    • 1970-01-01
    • 2022-11-15
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 2012-11-03
    • 2018-08-10
    • 1970-01-01
    相关资源
    最近更新 更多