It seems you want to get memdb via IO as a way to avoid passing more parameters, right? Then you ask if you can (A) define memdb , implying that it will be a top-level function, without the overhead of loading data from the database, or (B) if you can save the loaded data structure with a global scope.
Both of these can be done using IORef and unsafePerformIO to define a mutable top-level global variable. I DO NOT OFFER YOU THIS. This is inconvenient and annoying refactoring. However, I will show you, as in any case:
Assuming you have a function:
make_memdb :: IO (Map KV)
You can declare a top-level mutable variable:
import Data.Map as M import Data.IORef mRef :: IORef (Map KV) mRef = unsafePerformIO $ newIORef M.empty {-# NOINLINE mRef #-} main = do m <- make_memdb writeIORef mRef m ... do stuff using mRef ... stuffUsingMRef ... = do memdb <- readIORef let vs = map (memdb !) values return vs
Please note that your functions will live forever in IO . This is because you need IO to read the global mutable variable in which you placed memdb . If you donβt like it and donβt like the transmission options, then study the state monad! I am sure that in another answer we will discuss this, which is the right decision.
source share