我注意到 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/