评论者: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)))
`
Some text has been omitted.
`
(defn record->generator
([record]
; Is there a better way to do this?
(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)))))
`
Which enables me to extend a record like this
(记录定义 Foo [a b] LiteralGenerator (-literal->generator [this] (record->generator map->AbcDef this)))
我还没有考虑将这段代码整合进 test.check 的可能性。在进一步推进之前,我想听听大家对目前成果的反馈。