Function generator in test.check

137 Views Asked by At

I want to make a generators for functions.

I've noticed that there are indeed generators for IFn values, but when the function domain is infinite (and since the values are strict), it's not generally practical for them to be used as generators for functions.

Does this functionality exist or would I have to implement it myself?

2

There are 2 best solutions below

0
On BEST ANSWER

I think the answer depends on what sort of behavior you're expecting the function to have. In general you can use gen/let or gen/fmap to create arbitrary functions based on generated values. For example, you can generate a list of values and use it to construct a function that picks something from the list based on the hash of the input:

(gen/let [rets (gen/not-empty (gen/vector gen/any))]
  (fn [x]
    (rets (mod (hash x) (count rets)))))
2
On

Building on gfredericks answer to a more complete solution:

(defn fn-gen
  ([result-gen results-n result-scale]
   (gen/fmap
    (fn [results] (fn [& args] (get results (mod (apply + (map hash args)) results-n))))
    (gen/vector (gen/scale (partial + result-scale) result-gen) results-n)))
  ([result-gen result-n] (fn-gen result-gen result-n 10))
  ([result-gen] (fn-gen result-gen 10)))