使用Clojure Spec检查缺点的类型一致性?

时间:2018-05-27 19:15:27

标签: clojure clojure.spec

如果我与借阅者和书籍一起运行图书馆:

(s/def ::brs (s/coll-of ::br/borrower))
(s/def ::bks (s/coll-of ::bk/book))

我想要一个将项添加到任一集合的通用函数:

(defn add-item [x xs]
  (if (some #{x} xs)
    xs
    (cons x xs)))

如何编写规范以确保我无法向借阅者添加图书,反之亦然?

因为这个规范:

(s/fdef add-item
    :args (s/fspec :args (s/or :is-brs (s/and (s/cat :x ::br/borrower) (s/cat :xs ::brs))
                               :is-bks (s/and (s/cat :x ::bk/book) (s/cat :xs ::bks))))
    :ret (s/or :ret-brs ::brs
               :ret-bks ::bks))

无效。 : - (

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

使用::brs::bks的int /字符串定义:

(s/def ::brs (s/coll-of int?))
(s/def ::bks (s/coll-of string?))

这应该有效:

(s/fdef add-item
        :args (s/or
                :brs (s/cat :x int? :xs ::brs)
                :bks (s/cat :x string? :xs ::bks))
        :ret (s/or :brs ::brs
                   :bks ::bks))
;; instrument function here
(add-item 1 [2])
=> (1 2)
(add-item "1" [2]) ;; throws exception