评论者: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)))))
`
这使我能够扩展如下的记录
(defrecord Foo [a b] LiteralGenerator (-literal->generator [this] (record->generator map->AbcDef this)))
我至今还没有考虑将这段代码集成到test.check中的可能性。在进一步推进之前,我想先征求一下大家对目前成果的反馈。