[Haskell-beginners] Designing complex Haskell programs

Daniel Trstenjak daniel.trstenjak at gmail.com
Fri Jan 3 17:26:21 UTC 2014


Hi Courtney,

On Fri, Jan 03, 2014 at 04:45:08PM +0000, Courtney Robinson wrote:
> I currently can't wrap my head around how to maintain this state. How
> would a more experienced Haskeller approach this problem?

I think that it mostly boils down how your application loop should look
like or which implementation options you have.


If you're able to poll the received data, then you might just have something like:

appLoop :: AppState -> IO ()
appLoop appState = do
   appState' <- pollData appState
   appLoop appState'

You're reading the received data and modifying your state and then
recursive call appLoop.


If you want or have to use callbacks, then one option is to put your
application state into an IORef (a mutable variable), which is shared by
your application loop and your callback code e.g.:

main :: IO ()
main = do
   appRef <- newIORef AppState { ... }
   setWhateverCallback $ \receivedData ->
      modifyIORef appRef $ \appData ->
         -- modify your appData by receivedData

   appLoop appRef


appLoop :: IORef AppState -> IO ()
appLoop appRef = do
   modifyIORef appRef $ \appData ->
      -- do whatever you want with your appData

   appLoop appRef


If you're using multiple threads, then you might want to use
a MVar instead of an IORef.


Greetings,
Daniel


More information about the Beginners mailing list