Clojure Spec和“无法满足这样的条件-谓词经过100次尝试...”

时间:2018-06-25 22:57:29

标签: clojure clojure.spec

假设您有一个::givee和一个::giver

(s/def ::givee keyword?)
(s/def ::giver keyword?)

形成unq/gift-pair

(s/def :unq/gift-pair (s/keys :req-un [::givee ::giver]))

然后您有一个:unq/gift-history,它是vector的{​​{1}}:

unq/gift-pair

最后,假设您要替换(s/def :unq/gift-history (s/coll-of :unq/gift-pair :kind vector?)) 中的:unq/gift-pair之一:

vector

一切正常:

(defn set-gift-pair-in-gift-history [g-hist g-year g-pair]
  (assoc g-hist g-year g-pair))
(s/fdef set-gift-pair-in-gift-history
        :args (s/and (s/cat :g-hist :unq/gift-history
                            :g-year int?
                            :g-pair :unq/gift-pair)
                     #(< (:g-year %) (count (:g-hist %)))
                     #(> (:g-year %) -1))
        :ret :unq/gift-history)

直到我尝试(s/conform :unq/gift-history (set-gift-pair-in-gift-history [{:givee :me, :giver :you} {:givee :him, :giver :her}] 1 {:givee :dog, :giver :cat})) => [{:givee :me, :giver :you} {:givee :dog, :giver :cat}] 之前,

stest/check

我尝试使用(stest/check `set-gift-pair-in-gift-history) clojure.lang.ExceptionInfo: Couldn't satisfy such-that predicate after 100 tries. java.util.concurrent.ExecutionException: clojure.lang.ExceptionInfo: Couldn't satisfy such-that predicate after 100 tries. {} 来限制向量数(认为可能是问题),但没有成功。

关于如何正确运行s/int-in的任何想法?

谢谢。

1 个答案:

答案 0 :(得分:2)

问题在于向量的生成器和集合的索引是独立的/不相关的。随机向量和整数不满足以下条件:

#(< (:g-year %) (count (:g-hist %)))
#(> (:g-year %) -1)

要使用check这个函数,您可以提供一个自定义生成器,该生成器将生成随机的:unq/gift-history向量,并根据该向量的大小为索引构建另一个生成器:

(s/fdef set-gift-pair-in-gift-history
  :args (s/with-gen
          (s/and
            (s/cat :g-hist :unq/gift-history
                   :g-year int?
                   :g-pair :unq/gift-pair)
            #(< (:g-year %) (count (:g-hist %)))
            #(> (:g-year %) -1))
          #(gen/let [hist (s/gen :unq/gift-history)
                     year (gen/large-integer* {:min 0 :max (max 0 (dec (count hist)))})
                     pair (s/gen :unq/gift-pair)]
             [hist year pair]))
  :ret :unq/gift-history)

这是使用test.check的let宏,它比bind / fmap方便,它允许您使用看起来像常规{{1 }}。定制生成器将参数向量返回给函数。