A way to avoid a common use of unsafePerformIO

前端 未结 5 805
天命终不由人
天命终不由人 2021-01-03 23:37

I often find this pattern in Haskell code:

options :: MVar OptionRecord
options = unsafePerformIO $ newEmptyMVar

...

doSomething :: Foo -> Bar
doSomethi         


        
5条回答
  •  攒了一身酷
    2021-01-04 00:03

    I often find this pattern in Haskell code:

    Read different code.

    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.

    Sounds like literally exactly what the reader monad accomplishes, except that the reader monad does it in a safe way. Instead of accommodating your own laziness, just write actual good code.

提交回复
热议问题