I have a a 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With