Haskell monad for simulation

haskell

Solution

One simple way to do this would be brachiating along a lazy (possibly infinite) list instead of doing any explicit IO.

import Control.Monad.State

-- Prerequisites:

data SimState     -- coordinates & velocities.
data SimTVParams  -- what's read from input.   `instance Read`.

initialState :: SimState
simStep :: SimTVParams -> SimState -> SimState
simStateInfo :: SimState -> String

-- How to do the simulation:

main :: IO ()
main = interact $ 
          unlines . map simStateInfo
        . simulate initialState
        . map read . lines

simulate :: SimState -> [SimTVParams] -> [SimState]
simulate iState = (`evalState` iState) . mapM (state . step)
 where step params oldState = (newState, newState)
        where newState = simStep params oldState

Problem

What is the best way to represent state updated by input? I simulate physical system. It has state (coordinates, velocities). State is updated by simulation that takes some parameters (forces) from `stdin`. Result goes to `stdout` after each simulation cycle. Program should stop after N cycles. I've done it with `readIORef` and `writeIORef` but this is ugly.

Original source