Created
May 9, 2013 20:38
-
-
Save puffnfresh/5550437 to your computer and use it in GitHub Desktop.
Monad is a monoid.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Monoid m where | |
mappend :: m -> m -> m | |
mempty :: m | |
mconcat :: Monoid m => [m] -> m | |
mconcat = foldr mappend mempty | |
newtype MonadMonoid m a = | |
MonadMonoid { getMonad :: a -> m a } | |
instance Monad m => Monoid (MonadMonoid m a) where | |
mappend f g = MonadMonoid (\a -> getMonad f a >>= getMonad g) | |
mempty = MonadMonoid return | |
validations :: [MonadMonoid Maybe String] | |
validations = fmap MonadMonoid [ | |
\x -> if x == "Bad" then Nothing else Just x | |
, \x -> if x == "Invalid" then Nothing else Just x | |
] | |
main :: IO () | |
main = do | |
print . getMonad (mconcat validations) $ "Bad" | |
print . getMonad (mconcat validations) $ "Invalid" | |
print . getMonad (mconcat validations) $ "Good!" | |
{- | |
Nothing | |
Nothing | |
Just "Good!" | |
-} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can also use
Kleisli
fromControl.Arrow
and generalize:See also http://comonad.com/haskell/monoids/dist/doc/html/monoids/Data-Monoid-Categorical.html