Ingdas
Ingdas

Reputation: 1486

Top level mutable variables in haskell

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)

Upvotes: 9

Views: 789

Answers (1)

firefrorefiddle
firefrorefiddle

Reputation: 3805

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.

Upvotes: 11

Related Questions