Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 987
Ingdas Avatar asked Jun 04 '14 09:06

Ingdas


1 Answers

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.

like image 129
firefrorefiddle Avatar answered Sep 21 '22 05:09

firefrorefiddle