ericky
ericky

Reputation: 1681

Use Clojure Spec to check type consistency on a cons?

If I run a library with borrowers and books:

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

And I want a generic function that adds an item to either collection:

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

How do I write a spec that makes sure I can't add a book to borrowers and vice versa?

Because this spec:

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

is not working. :-(

Thank you for your help!

Upvotes: 1

Views: 85

Answers (1)

Taylor Wood
Taylor Wood

Reputation: 16194

Using int/string definitions for ::brs and ::bks:

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

This should work:

(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

Upvotes: 2

Related Questions