【问题标题】:Use Clojure Spec to check type consistency on a cons?使用 Clojure Spec 检查缺点的类型一致性?
【发布时间】:2018-05-27 19:15:26
【问题描述】:

如果我经营一个有借书人和书籍的图书馆:

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

不工作。 :-(

感谢您的帮助!

【问题讨论】:

    标签: clojure clojure.spec


    【解决方案1】:

    使用 ::brs::bks 的 int/string 定义:

    (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
    

    【讨论】:

    • 确实如此,而且简单得多。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 2020-03-20
    • 1970-01-01
    相关资源
    最近更新 更多