Yet Another Haskell Tutorial の続き4

Yet Another Haskell Tutorial のExerciseの続きです。そして、今回で最後です。最後のMonadの章は、説明が短すぎてコードをどうやったら動かすかから考えないとならない状態で、あまり理解できてないので別に本を買った方がよさそうですね。
しかし、とりあえずProject EulerHaskellで解くことはできそうなので YAHTはこれにて終了です。

Exercise 9.1 Verify that Maybe obeys the three monad laws.

module Maybe where

newtype Maybe a = Just a | Nothing

instance Monad (Maybe a) where
    return a      = Just a
    Just a  >>= f = f a
    Nothing >>= f = Nothing
    fail _        = Nothing

-- law.1: return a >>= f := f a
--     return a >>= f
-- ==> Just a   >>= (\x -> f x)
-- ==> (\x -> f x) a
-- ==> f a

-- law.2: f >>= return := f
--     f >>= return
-- ==> f >>= \x -> Just x
---- f return Nothing.
-- ==> Nothing >>= return
-- ==> Nothing
-- ==> f
---- f return Just a
-- ==> Just a >>= \x -> Just x
-- ==> (\x -> Just x) a
-- ==> Just a
-- ==> f

-- law.3: f >>= (\x -> g x >>= h) := (f >>= g) >>= h
-- if f return Nothing.
-- LHS return Nothing and RHS return 'Nothing >>= h' ==> Nothing.
-- if f return Just a.
-- LHS: g a >>= h, RHS: g a >>= h.

Exercise 9.2 The type Either String is a monad that can keep track of errors. Write an
instance for it, and then try doing the search from this chapter using this monad.
Hint: Your instance declaration should begin: instance Monad (Either String)
where.

instance Monad (Either String) where
    return a      = Left a
    Left  a >>= f = f a
    Right a >>= _ = Right a
    fail a        = Right a