gpt4 book ai didi

haskell - 在纯代码中避免 IORef

转载 作者:行者123 更新时间:2023-12-03 10:40:53 26 4
gpt4 key购买 nike

我注意到 Data.UnionFind使用 IO monad 通过 IORefs 提供指针。我想每个人都高兴地调用unsafePerformIO在纯代码中本地使用它时,因为数据结构很好理解,但是..

这种数据结构是否有规范的清洁方法?也许是 IO 的包装器使不可避免的 unsafePerformIO通过禁止大多数 IO 操作来减少不安全的“查找”?

最佳答案

Is there a canonical cleaner approach to such data structures? Perhaps a wrapper around IO that makes the inevitable unsafePerformIO less unsafe "looking" by prohibiting most IO operations?



是的,确切地说。你刚刚发明了 the ST monad , 由 Launchbury and Peyton Jones 介绍大约20年前。
ST monad 只允许局部范围的内存效果。值得注意的是,它使用类型系统来保证副作用在使用它们的代码块范围之外是不可见的。

因此,只要您仅通过引用使用内存,仅在本地范围内,您就可以避免 unsafePerformIO并改用纯 ST,例如 implement union-find .

关于haskell - 在纯代码中避免 IORef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10298664/

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