haskell - Overflow problems in dealing with IO and MonadRandom and chained computations -


so have computation step takes in previous result , outputs rand g path, path custom data type (think of traveling salesman kind of problem). i'm letting monadrandom handle of generator passing , stuff.

i want find the, say, nth composition of computation upon itself. right i'm using

thecomputation :: (randomgen g) => rand g path thecomputation = (iterate (>>= step) (return startingpath)) !! n 

and print out run

main =   res <- evalrandio thecomputation   print res 

however, have problem

if pick high enough n (i need on order of 10^6), stack overflow.

i've managed track problem fact thecomputation heavily composed (nested?) io object. it's series of io computations , ghc has keep track of of layers of nested io's, , after enough layers, gives up.

how supposed deal this? in imperative language there isn't this. should here? should force of io's evaluate or ...?

there similar question on site wasn't able helpful out of accepted answer i'm still pretty lost

concrete example

import system.random import control.monad.random import control.monad  data path = doublepath double deriving show  step :: (randomgen g) => path -> rand g path step (doublepath x) =   dx <- getrandom   return (doublepath ((x + dx)/x))  thecomputation :: (randomgen g) => rand g path thecomputation = (iterate (>>= step) (return (doublepath 10.0))) !! 1000000  main =   result <- evalrandio thecomputation   print result 

does overflow on computer

you bitten lazyness: everytime call step on value x, ghc creating thunk step x not evaluated until final value required.

a simple fix make step strict in argument, e.g. pattern-matching on doublepath !x (and using -xbangpatterns) or inserting x `seq` before body of function. code finished without stack overflow (heh).


Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -