Wednesday, 15 June 2011

Haskell State monadic function using recursion -



Haskell State monadic function using recursion -

tl:dr: there way illustration 3 without passing argument

i'm trying understand state monad in haskell (control.monad.state). made extremely simple function:

example 1

example :: state int int illustration = e <- set (e*5) homecoming e

this illustration works in ghci...

runstate illustration 3 (3,15)

i modified able take arguments....

example 2

example :: int -> state int int illustration n = e <- set (e*n) homecoming e

also works in ghci...

runstate (example 5) 3 (3,15)

i made recursive, counting number of steps takes computation satisfy condition

example 3

example :: int -> state int int illustration n = e <- if (n /= 1) set (succ e) illustration (next n) else homecoming (succ e) next :: int -> int next n | n = div n 2 | otherwise = 3*n+1

ghci

evalstate (example 13) 0 10

my question is, there way previous illustration without explicitly passing value?

you can store n in state along side of e, example, like:

example = (e,n) <- if n /= 1 set (succ e, next n); illustration else homecoming e

there overhead using state monad, should compare alternatives.

for instance, more haskelly way of approaching problem compose list operations compute answer, e.g.:

collatz :: int -> [int] collatz n = iterate next n collatzlength n = length $ takewhile (/= 1) $ collatz n

haskell recursion monads state-monad

No comments:

Post a Comment