2

I have a simulation where the result of each step is the input for the next step. The simulation itself uses the IO Monad (Repa:ComputeP) and I would like to write the result of each step to a file as it is running.

The closest I can think of using is the iterateM_ action on my simulation step, but this will run forever. Is there a way to only call the iterateM_ a specific number of times?

Relevant code:

main :: IO ()
main = do
  us <- iterateM_ (\u -> (computeP (simulStep u) :: IO (Array U DIM2 Double))) u0
  zipWithM_ writeMatrixToTextFile (map show [1..]) us

(Or is there a better alternative for what I would like to do)

Zeta
  • 103,620
  • 13
  • 194
  • 236
user668074
  • 1,111
  • 10
  • 16
  • 1
    There's `iterateUntilM_` in the same package. – zakyggaps Feb 19 '16 at 05:41
  • I guess this works, it requires the evolving function to have a wrapper to keep track of the counter. Do you know of a more elegant way? – user668074 Feb 19 '16 at 09:58
  • 2
    If your evolving function will work on delayed repa arrays then you can repeat and compose your function, apply it to the array once instead of make a whole concrete intermediate array every step in IO monad. I believe repa is more optimized than monad-loops that way. – zakyggaps Feb 19 '16 at 10:29
  • This seems like a good method, but does it provide a convenient way to save the intermediate results? – user668074 Feb 19 '16 at 14:36
  • If you want all the intermediate results then `iterateNM` in [vector](http://hackage.haskell.org/package/vector-0.11.0.0/docs/Data-Vector-Fusion-Stream-Monadic.html#v:iterateNM) package will iterate exactly n times and restore all the results in a lazy stream. – zakyggaps Feb 19 '16 at 15:11
  • As follow up, `iterateUntilM_` worked for me. I wrapped the function with a counter. If you want you can submit that as the answer and I can mark it as correct. – user668074 Feb 23 '16 at 00:44
  • 1
    It's very kind of you, but as I almost got no details from your question, what I made so far are effectively suggestions, not answers. BTW It will be great if you can conclude your (simplified) code as an answer and show the reason of your decision, for someone it may save the day one day. – zakyggaps Feb 23 '16 at 11:58

0 Answers0