[Haskell-cafe] Applicative/Monad for Either

Tony Morris tmorris at tmorris.net
Wed Jan 21 17:03:52 EST 2009


-----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" -- ?

- --
Tony Morris
http://tmorris.net/

S, K and I ought to be enough for anybody.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFJd5vImnpgrYe6r60RAoUNAJ4jn0GfC6zsP9giPGop1ILExiHrLQCfSoc2
0QXf533sWb3HyrL0pQNjMww=
=R36O
-----END PGP SIGNATURE-----



More information about the Haskell-Cafe mailing list