haskell - 在纯代码中避免 IORef

标签 haskell data-structures monads union-find ioref

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

相关文章:

haskell - 为什么 Yesod 中没有 ToJSON/FromJSON 的 Persistent 类型实例?

data-structures - Lucene (Solr/ElasticSearch) 是如何快速进行过滤词条计数的?

data-structures - 为什么动态数组总是翻倍 2 倍?

java - 从巨大的集合中遍历和分组相似对象的有效方法

list - 我的递归列表构造有什么问题?

haskell - 为什么询问从 Reader monad 检索环境

haskell - "succ(zero)"的类型与 GHC 中的 "one"的类型不同

haskell - yesod-bin 缺少(未知)依赖项?

Haskell:join 是如何自然转变的?

haskell - 如何在 Haskell 中处理大量常量?