Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Haskell Nomads

Name: Anonymous 2008-09-23 13:47

So can anybody tell me in a way one can understand it what a fucking monad does?

Name: Anonymous 2008-09-25 18:25

>>40
There's nothing to it, really. Monads allow you to express a purely functional computation while keeping some aspect of that computation hidden or implicit. For example, if you wanted to write a function that returns a list of n random numbers using the function random :: (RandomGen g, Random a) => g -> (a, g), you'd write something like this:

nRandoms n gen
   | n <= 0 = ([], gen)
   | otherwise = (r:rs, gen'')
   where
      (r, gen') = random gen
      (rs, gen'') = nRandoms (n - 1) gen'


See how you have to explicitly handle the "state changes" of the random generator by passing it around? Well, if you turn the random function into a State monad:

randomS :: (RandomGen g, Random a) => State g a
randomS = State random


then you can write nRandoms like this:

nRandomsS n
   | n <= 0 = return []
   | otherwise = liftM2 (:) randomS (nRandomsS (n - 1))

nRandoms n gen = runState (nRandomsS n) gen


or even like this:

nRandoms n gen = runState (replicateM n randomS) gen


What this particular monad, the State monad, does is handle the state changes implicitly, so you don't have to worry about it. Here's (part of) the definition of that monad, see how simple it is:

newtype State s a = State { runState :: s -> (a, s) }

instance Monad (State s) where
    return a = State $ \s -> (a, s)
    m >>= k  = State $ \s -> let (a, s') = runState m s
                                 in runState (k a) s'


Hope this helps clear things up for you.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List