[Haskell-cafe] Applicative/Monad for Either
Daniel Fischer
daniel.is.fischer at web.de
Wed Jan 21 17:19:49 EST 2009
Am Mittwoch, 21. Januar 2009 23:03 schrieb Tony Morris:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> In the code below, the Applicative instance accumulates on the Left
> constructor using Monoid/mappend.
> Is it possible to write an equivalent Monad such that ap = (<*>) ? I'm
> finding difficulty in proving to myself either way.
>
>
>
>
> import Control.Monad.Instances
> import Control.Applicative
> import Data.Monoid
>
> newtype Z e a = Z {
> either :: Either e a
> }
>
> instance Functor (Z e) where
> fmap f (Z e) = Z (f `fmap` e)
>
> instance (Monoid e) => Applicative (Z e) where
> pure = Z . Right
> (Z (Left e1)) <*> (Z (Left e2)) = Z (Left (e1 `mappend` e2))
> (Z (Left e1)) <*> (Z (Right _)) = Z (Left e1)
> (Z (Right _)) <*> (Z (Left e2)) = Z (Left e2)
> (Z (Right f)) <*> (Z (Right a)) = Z (Right (f a))
>
> instance (Monoid e) => Monad (Z e) where
> return = pure
> (Z e) >>= f = error "todo" -- ?
>
I think
Z (Left e) >>= f = Z (Left e)
Z (Right a) >>= f = f a
would be the only choice.
More information about the Haskell-Cafe
mailing list