评论者: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中。在进一步开展此项工作之前,我希望得到一些关于我所做工作的反馈。