Three useful monads

Writer

newtype Writer w a = Writer { runWriter :: (a, w) }


instance (Monoid w) => Monad (Writer w) where

    return x = Writer (x, mempty)

    (Writer (x,v)) >>= f = let (Writer (y, v')) = f x

                                      in Writer (y, v `mappend` v')


write1 >>= func = do 

    let (val1, logs1) = runWriter writer1

         (val2, logs2) = runWriter$func val1

    writer(val2, logs1 ++ logs2)


例子

importControl.Monad.Writer


logNumber::Int->Writer[String]Int

logNumber x=Writer(x, ["Got number: "++show x])


multWithLog::Writer[String]Int

multWithLog=do

    a<-logNumber3

    b<-logNumber5

    return (a*b)



Reader

data Reader r a = Reader { runReader :: r -> a}

the function monad is also called read monad

instanceMonad((->) r)where

return x=\_->x

h>>=f=\w->f (h w) w


example:

importControl.Monad.Instances

addStuff :: Int->Int

addStuff = do

    a<-(*2)

    b<-(+10)

    return (a+b)

ghci>addStuff 3

19

其实read monad也很好理解,它的context就是传入参数



The State Monad

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


instance Monad (State s) where 

    return x = State $ \s -> (x, s)

    (State h) >> f = State $ \s -> let (a, newState) = h s 

                                                       (State g) = f a

                                                   in g newState


m >>= k = State $ \s -> let (a, s') = runState m s

                                        in runState (k a) s'

你可能感兴趣的:(Three useful monads)