Top level mutable variables in haskell

I have aa C++ program calling my Haskell program multiple times. But some data from the first calls needs to be retained for the subsequent calls. I know top-level mutable variables are not supported by default in Haskell but I guess I still need something like that. (Writing my state to a file and reading it back in would work, but I want something more native)

On hackage I found libraries like global-variables or safe-globals but they all seem quite old and dependent on old versions of packages I already use. Is there a canonical solution for this problem?

Ideally, I'd like to have the top-level functions:

getState :: IO Mystate
writeState :: Mystate -> IO ()

(I guess I should also mention that everything is done in one call of hs_init() in the FFI so the Haskell program doesn't really exit between calls)


You can create a global mutable variable:

myGlobalVar :: IORef Int
{-# NOINLINE myGlobalVar #-}
myGlobalVar = unsafePerformIO (newIORef 17)

The haskell wiki gives this as current standard solution, while also discussing alternatives.

链接地址: http://www.djcxy.com/p/43246.html

上一篇: Haskell可以对不同类型的IO进行区分

下一篇: haskell中的顶级可变变量