【问题标题】:Using spec/merge with spec/multi-spec使用规范/合并与规范/多规范
【发布时间】:2019-02-08 19:39:33
【问题描述】:

我可以将s/merge 与s/multi-spec 一起使用吗?例如

(require '[clojure.spec :as s])

(s/def :field/common (s/keys :req-un [:field/type :field/name]
                             :opt-un [:field/default]))

(s/def :field/max-length int?)

(defmulti field-type :type)
(defmethod field-type :character [_]
  (s/merge :field/common
           (s/keys :req-un [:field/max-length])))
(defmethod field-type :foreign-key [_]
  (s/merge :field/common
           (s/keys :req-un [:field/references])))
(defmethod field-type :int [_]
  ;; ??? what to do here? - I only want the common keys
  :field/common)
(defmethod field-type :boolean [_]
  ;; ??? what to do here? - I only want the common keys
  :field/common)

(s/def ::field (s/multi-spec field-type :field/type))

我会为:int 和:boolean 方法添加什么?我只需要常用字段。

【问题讨论】:

    标签: clojure clojure.spec


    【解决方案1】:

    不确定这是否是您想要的,但我认为您会使用普通的多方法继承方法。

    (require '[clojure.spec :as s])
    
    (s/def :field/common (s/keys :req-un [:field/type :field/name]
                                 :opt-un [:field/default]))
    
    (s/def :field/max-length int?)
    
    (defmulti field-type :type)
    (defmethod field-type :character [_]
      (s/merge :field/common
               (s/keys :req-un [:field/max-length])))
    (defmethod field-type :foreign-key [_]
      (s/merge :field/common
               (s/keys :req-un [:field/references])))
    
    (defmethod field-type :field/common [_]
      :field/common)
    
    (derive :int :field/common)
    (derive :boolean :field/common)
    
    (s/def ::field (s/multi-spec field-type :field/type))
    

    【讨论】:

    • 如果它有效,我喜欢它。谢谢,我试试看!
    猜你喜欢
    • 2017-05-31
    • 2016-05-13
    • 2018-06-06
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    相关资源
    最近更新 更多