Avoiding IORefs in pure code

僤鯓⒐⒋嵵緔 提交于 2019-12-03 01:18:29
Don Stewart

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?

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!