避免共同使用unsafePerformIO的一种方法 [英] A way to avoid a common use of unsafePerformIO

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

问题描述

  options :: MVar OptionRecord 
options = unsafePerformIO $ newEmptyMVar

...

doSomething :: Foo - > Bar
doSomething = unsafePerformIO $ do
opt< - readMVar options
doSomething'where ...

基本上,有一个选项或类似的记录,最初是在程序开始时设置的。由于程序员很懒,他不想在整个程序中执行选项记录。他定义了一个 MVar 来保留它 - 通过丑陋地使用 unsafePerformIO 来定义它。程序员确保在任何操作发生之前只设置一次状态。现在,程序的每个部分都必须再次使用 unsafePerformIO 来解压缩选项。



在我看来,这样一个变量被认为是实用的纯粹的(不要殴打我)。是否有一个库将这个概念抽象出来并确保变量只设置一次,即在初始化之前没有调用完成,并且不需要编写 unsafeFireZeMissilesAndMakeYourCodeUglyAnd DisgustingBecauseOfThisLongFunctionName

解决方案

类似的,你为什么不试试读者monad?

  foo :: ReaderT OptionRecord IO()
foo = do
options< - ask
fireMissiles

main = runReaderT foo(OptionRecordfoo)

(如果您不需要IO:P,则为普通阅读器)


I often find this pattern in Haskell code:

options :: MVar OptionRecord
options = unsafePerformIO $ newEmptyMVar

...

doSomething :: Foo -> Bar
doSomething = unsafePerformIO $ do
  opt <- readMVar options
  doSomething' where ...

Basically, one has a record of options or something similar, that is initially set at the program's beginning. As the programmer is lazy, he doesn't want to carry the options record all over the program. He defines an MVar to keep it - defined by an ugly use of unsafePerformIO. The programmer ensures, that the state is set only once and before any operation has taken place. Now each part of the program has to use unsafePerformIO again, just to extract the options.

In my opinion, such a variable is considered pragmatically pure (don't beat me). Is there a library that abstracts this concept away and ensures that the variable is set only once, i.e. that no call is done before that initialization and that one doesn't have to write unsafeFireZeMissilesAndMakeYourCodeUglyAnd DisgustingBecauseOfThisLongFunctionName

解决方案

If you are using MVar for holding settings or something similar, why don't you try reader monad?

foo :: ReaderT OptionRecord IO ()
foo = do
    options <- ask
    fireMissiles

main = runReaderT foo (OptionRecord "foo")

(And regular Reader if you don't require IO :P)

这篇关于避免共同使用unsafePerformIO的一种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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