使用规范/与规范/多规范合并

时间:2019-02-08 19:39:34

标签: clojure clojure.spec

我可以将s/merges/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方法,我该怎么办?我只需要公共字段。

1 个答案:

答案 0 :(得分:2)

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

(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))