gpt4 book ai didi

clojure - 在嵌套函数中设置可变字段 - deftype - clojure

转载 作者:行者123 更新时间:2023-12-04 04:45:34 25 4
gpt4 key购买 nike

编辑:
在发布我的问题的先前版本后,我发现真正的问题在于嵌套函数。

如果我在 deftype 中有一个闭包我无法从该闭包中更新任何可变字段。

例如。以下作品:

(deftype Test [^:unsynchronized-mutable x]
TestInterface
(perform [this o] (set! x o)))

但这不会:
(deftype Test [^:unsynchronized-mutable x]
TestInterface
(perform [this o] (fn [] (set! x o)) nil)) ; throws a compiler error about assigning to non-mutable field

有什么办法可以到达并进入该领域?做 (set! (.x this) o)结果是:

ClassCastException user.Test 无法转换为 compile__stub.user.Test user.Test/fn--152 (NO_SOURCE_FILE:3

尝试运行代码时。
TestInterface 的代码为了完整性:
(definterface TestInterface (perform [o]))

最佳答案

考虑到不起作用的版本,如果它确实起作用,会返回一个闭包,该闭包可能会逃到野外并从任何地方被调用,从而设置您不同步的本地并把事情搞得一团糟。

如果你坚持做这种事情,你总是可以为你的可变字段创建一个带有 setter 的接口(interface),在你的类型中实现它,并在你需要设置这个字段的任何地方调用 setter。

直接变异 ((set! (.-x foo) ...)) 不起作用,因为 Clojure 类型的可变字段(非同步和易失)是私有(private)的。

关于clojure - 在嵌套函数中设置可变字段 - deftype - clojure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18236241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com