避免使用纯代码中的IORefs [英] Avoiding IORefs in pure code

查看:107
本文介绍了避免使用纯代码中的IORefs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I noticed that Data.UnionFind uses the IO monad to provide pointers via IORefs. I imagine everyone happily calls unsafePerformIO when using it locally in pure code, since the data structure is so well understood, but ..

这种数据结构是否有规范的清洁方法?也许IO周围的包装,通过禁止大多数IO操作,使不可避免的 unsafePerformIO 更不安全的寻找?

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?

推荐答案


这种数据结构是否有规范的清洁方法?也许一个IO的封装,通过禁止大多数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?

是的,准确地说。您刚刚发明了 ST monad ,由 Launchbury和Peyton Jones 大约在20年前。

Yes, precisely. You have just invented the ST monad, introduced by Launchbury and Peyton Jones some 20 years ago.

ST monad仅允许本地 - 范围记忆效应。值得注意的是,它使用类型系统来保证副作用在使用它们的代码块的范围之外是不可见的。

The ST monad allows only locally-scoped memory effects. It is remarkable in that it uses the type system to guarantee that side effects are not visible outside of the scope of the code block that is using them.

因为您仅通过引用使用内存,只能在本地范围内,您可以避免 unsafePerformIO ,并使用纯ST替代,例如实现union-find

So, as long as you use memory only via references, only in local scope, you can avoid unsafePerformIO and use pure ST instead, for example, to implement union-find.

这篇关于避免使用纯代码中的IORefs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆