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-26 8:03

>>57
Let's implement side effects in Haskell without using Monads. Haskell is a pure language, so all side effects must be explicit. To do that we first define a datatype
data World = World ...
World contains all the state of the runtime environment. Now if we want to write a function that modifies this state, we must pass the state to the function and then it returns a value and a new state. So we would define getChar as
getChar :: World -> (Char, World)
and putChar as
putChar :: World -> ((), World)
putChar doesn't have any return value so we return () which is just the same as void in C.

Now we want to use these function to write a function cat, which copies it input to the output. cat has side effects so it gets a state as a paramater and returns () and a new state.
cat :: World -> ((), World)
cat s0 = let (x, s1) = getChar s0
         in if x == EOF
            then ((), s1)
            else let (y, s2) = putChar s1
                 in cat s2


You can probably see that this explicit passing of state can get ugly real quick. Monads allow us to hide this. We define a datatype IO as
data IO a = IO (World -> (a, World))
which is any function which has a side effect and returns a value of type a. So now our getChar and putChar are defined as
getChar :: IO Char
putChar :: IO ()


To make IO into a Monad we must implement the functions of >>45.
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))


Now we can write our cat function as
cat :: IO ()
cat = getChar >>= (\x -> if x == EOF
                         then return ()
                         else putChar x >> cat)


Or using the do-notation as syntactic sugar
cat :: IO ()
cat = do x <- getChar
      if x == EOF
         then return ()
         else do putChar
                 cat

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