评论者:pangloss
今天我在REPL中试验了一些代码,可以将任意文字转换为生成器
`
(defprotocol LiteralGenerator
(-literal->generator [literal]))
(defn literal->generator [literal]
(cond
(satisfies? LiteralGenerator literal) (-literal->generator literal)
(vector? literal) (apply gen/tuple (mapv literal->generator literal))
(and (map? literal) (= [:gen] (keys literal)) (fn? (:gen literal))) literal
(map? literal) (gen/fmap (partial into {}) (literal->generator (mapv vec literal)))
(set? literal) (gen/fmap set (literal->generator (vec literal)))
(list? literal) (gen/fmap (partial apply list) (literal->generator (vec literal)))
:else (gen/return literal)))
`
从记录生成可能是一般有用的,所以我添加了这个功能
`
(defn record->generator
([record]
有无更好的方法来做这个?
(let [ctor (eval (read-string (str "map->" (last (clojure.string/split (str (class record)) #"\.")))))]
(record->generator ctor record)))
([ctor record]
(gen/fmap ctor (literal->generator (into {} record)))))
`
这使我可以扩展这样一个记录:
(定义记录 Foo [a b] LiteralGenerator,使用 (-literal->generator [this] (record->generator map->AbcDef this)))
我还完全没有考虑将此代码嵌入 test.check 的可能性。在进一步深入研究之前,我想先得到关于我目前所做工作的反馈。