我第一次使用deftype是因为我正在编写优先级队列,而defrecord正在干扰实现ISeq。
为了避免需要“解构”类,修改字段,并通过对其构造函数的显式调用“重构”,我发现自己需要为每个需要alter的字段编写update-like函数。
(deftype Priority-Queue [root size priority-comparator])
(defn- alter-size [^Priority-Queue queue, f]
(->Priority-Queue (.root queue) (f (.size queue)) (.priority_comparator queue)))
(defn- alter-root [^Priority-Queue queue, f]
(->Priority-Queue (f (.root queue)) (.size queue) (.priority_comparator queue)))当然,我可以编写一个函数来允许一个更接近update的语法,但这一点的需要似乎有点难闻。
这是改变非记录的典型方法吗?我已经在其他地方提取了尽可能多的内容,所以我实际上需要修改队列本身的次数仅限于几个地方,但仍然感觉很笨重。是编写类似于用于案例类的函数/宏的唯一干净解决方案。
发布于 2018-05-31 14:27:48
我建议对此做一些宏观上的调整。最后我得到了这个:
(defmacro attach-updater [deftype-form]
(let [T (second deftype-form)
argnames (nth deftype-form 2)
self (gensym "self")
k (gensym "k")
f (gensym "f")
args (gensym "args")]
`(do ~deftype-form
(defn ~(symbol (str "update-" T))
^{:tag ~T} [^{:tag ~T} ~self ~k ~f & ~args]
(new ~T ~@(map (fn [arg]
(let [k-arg (keyword arg)]
`(if (= ~k ~k-arg)
(apply ~f (. ~self ~arg) ~args)
(. ~self ~arg))))
argnames))))))它只处理deftype表单的arg列表,并创建函数update-%TypeName%,该函数具有与简单update相似的语义,使用字段名的关键字变体,并返回对象的克隆,其中包含修改后的字段。
简单的例子:
(attach-updater
(deftype MyType [a b c]))它扩展到以下方面:
(do
(deftype MyType [a b c])
(defn update-MyType [self14653 k14654 f14655 & args14656]
(new
MyType
(if (= k14654 :a)
(apply f14655 (. self14653 a) args14656)
(. self14653 a))
(if (= k14654 :b)
(apply f14655 (. self14653 b) args14656)
(. self14653 b))
(if (= k14654 :c)
(apply f14655 (. self14653 c) args14656)
(. self14653 c)))))可以这样使用:
(-> (MyType. 1 2 3)
(update-MyType :a inc)
(update-MyType :b + 10 20 30)
((fn [item] [(.a item) (.b item) (.c item)])))
;;=> [2 62 3]
(attach-updater
(deftype SomeType [data]))
(-> (SomeType. {:a 10 :b 20})
(update-SomeType :data assoc :x 1 :y 2 :z 3)
(.data))
;;=> {:a 10, :b 20, :x 1, :y 2, :z 3}您还可以避免为每种类型生成update-%TypeName%函数,使用协议(例如Reconstruct)并在宏中自动实现它,但这将使您失去使用varargs的可能性,因为协议函数不支持它们(例如,您无法这样做:(update-SomeType :data assoc :a 10 :b 20 :c 30) )。
更新
还有一种方法,我可以避免使用宏在这里。虽然它是骗人的(因为它使用了->Type构造函数的元数据),而且可能也很慢(因为它也使用反射)。但它仍然有效:
(defn make-updater [T constructor-fn]
(let [arg-names (-> constructor-fn meta :arglists first)]
(fn [self k f & args]
(apply constructor-fn
(map (fn [arg-name]
(let [v (-> T (.getField (name arg-name)) (.get self))]
(if (= (keyword (name arg-name))
k)
(apply f v args)
v)))
arg-names)))))它可以这样使用:
user> (deftype TypeX [a b c])
;;=> user.TypeX
user> (def upd-typex (make-updater TypeX #'->TypeX))
;;=> #'user/upd-typex
user> (-> (TypeX. 1 2 3)
(upd-typex :a inc)
(upd-typex :b + 10 20 30)
(#(vector (.a %) (.b %) (.c %))))
;;=> [2 62 3]https://stackoverflow.com/questions/50611521
复制相似问题