
Am Mittwoch, 17. September 2008 20:05 schrieb Mike Sullivan:
Hi All,
As I'm sure all Haskell beginners do, I'm having a bit of a struggle wrapping my head around all of the uses for monads. My current frustration is trying to figure out how to use the state monad to attach some persistent state between different calls to a function. I have two questions that I would appreciate it if somebody could help me with.
The ubiquitous state monad example for Haskell tutorials seems to be a random number generator, with a function like the following (from http://www.haskell.org/all_about_monads/html/statemonad.html#example):
getAny :: (Random a) => State StdGen a getAny = do g <- get (x,g') <- return $ random g put g' return x
My first question is very basic, but here it goes: I see it everywhere, but what does the "=>" signify? Specifically, in this example what does "(Random a) =>" do in the type signature?
It describes a required context, here it means "for any type 'a' which is an instance of the typeclass Random, getAny has the type State StdGen a".
My second question is more of a request, I suppose. I think it would be useful to get another example that does not have the added complications of dealing with the Random package, and saves more than one piece of data as state. How would one go about (for example) creating a Fibonacci sequence generator that saves the last state, such that on each call it returns the next number in the Fibonacci sequence?
data FibState = F {previous, current :: Integer} fibState0 = F {previous = 1, current = 0} currentFib :: State FibState Integer currentFib = gets current nextFib :: State FibState Integer nextFib = do F p c <- get let n = p+c put (F c n) return n does that help?
Thank you, Mike
Cheers, Daniel