haskell - Calling a function with new values whilst looping -


i trying write function loops 100 times , in loop calls function called pricejump. when loop first started price argument function takes initial value of 100. after every loop, function produces new price should passed pricejump function.

i have tried code logic unsuccessfully (code below). problem code produce new price in monadic way , value of type m double m constrained type class primmonad.

i'm not doing in idiomatic haskell why experiencing these problems pointers in right direction appreciated also. summarise main goal call pricing function initial price passed in , every new price generates new price should passed it.

import control.monad.state import control.monad.primitive import system.random.mwc import system.random.mwc.distributions  pricejump :: double -- price           -> double -- rate           -> double -- vol           -> double -- ts           -> double -- rnd           -> double -- new price pricejump price rate vol ts rnd = price * (1 + (rate * ts) + (vol * sqrt(ts) * rnd))  loop :: primmonad m => gen (primstate m) -> int -> double -> double -> double -> double -> m double loop gen turns price rate vol ts   | turns <= 0 = (pricejump price rate vol ts) <$> (normal 0 1 gen)   | turns == 100 = (pricejump price rate vol ts) <$> (normal 0 1 gen)   | otherwise  = loop gen (turns - 1) (pricejump price rate vol ts) <$> (normal 0 1 gen) rate vol ts 

thinking in terms of loops in haskell useful. if want repeat k times, should reach replicate , like. in case, want repeat function takes price , produces new price 100 times (and performs computation in monad), sequence in long chain.

with in mind, code becomes

loop :: primmonad m => gen (primstate m) -> int -> double -> double -> double -> double -> m double loop gen turns price rate vol ts    = foldr (>=>)            return            (replicate turns (\p -> pricejump p rate vol ts <$> normal 0 1 gen))            price  

it turns out kleisli composition (>=> :: monad m => (a -> m b) -> (b -> m c) -> -> m c) need here. in way can see >=> being regular function composition, inside monad.

another option generate random values in advance, deal pure values there - i.e pure fold on list of random seeds. code doesn't end looking different:

loop gen turns price rate vol ts     = foldr (\rnd p -> pricejump p rate vol ts rnd) price <$>       replicatem turns (normal 0 1 gen)   

Comments