Name: Anonymous 2008-09-23 13:47
So can anybody tell me in a way one can understand it what a fucking monad does?
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'random function into a State monad:
randomS :: (RandomGen g, Random a) => State g a
randomS = State randomnRandoms like this:
nRandomsS n
| n <= 0 = return []
| otherwise = liftM2 (:) randomS (nRandomsS (n - 1))
nRandoms n gen = runState (nRandomsS n) gen
nRandoms n gen = runState (replicateM n randomS) genState 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'
(>>=) :: Monad m => m a -> (a -> m b) -> m b
(>>) :: Monad m => m a -> m b
return :: Monad m => a -> m a
return a >>= f == f a
m >>= return == m
(m >>= f) >>= g == m >>= (\a -> f a >>= g)
data World = World ...getChar :: World -> (Char, World)putChar :: World -> ((), World)cat :: World -> ((), World)
cat s0 = let (x, s1) = getChar s0
in if x == EOF
then ((), s1)
else let (y, s2) = putChar s1
in cat s2data IO a = IO (World -> (a, World))getChar :: IO Char
putChar :: IO ()instance Monad (IO a) where
IO m >>= f = IO (\s0 -> let (x, s1) = m s0
IO m' = f x
in m' s1)
IO m >> IO m' = IO (\s0 -> let (x, s1) = m s0
in m' s1)
return x = IO (\s0 -> (x, s0))cat :: IO ()
cat = getChar >>= (\x -> if x == EOF
then return ()
else putChar x >> cat)cat :: IO ()
cat = do x <- getChar
if x == EOF
then return ()
else do putChar
cat
darcs, after I found out that it systematically chokes on even the most elementary operations*.fib or fact like every other Haskell programmer''?