Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instance Monoid Monad

Tags:

haskell

monads

Monad is a monoid, however it's a monoid in a different way than, say, Integer. I wonder if there is a way to write Monoid' and Monad' such that both Integer and Monad' can be expressed as instances of the same Monoid' typeclass?

like image 990
Karolis Juodelė Avatar asked Jun 20 '13 04:06

Karolis Juodelė


2 Answers

So, let's pick a particular way Integer has a Monoid

instance Monoid Int where
  zero = 0
  plus = (+)

and now here's a Monad Monoid

{-# LANGUAGE FlexibleInstances #-}
instance Monad m => Monoid (Kleisli m a a) where
  zero = id
  plus = (.)

and here's another

instance MonadPlus m => Monoid (m a) where
  zero = mzero
  plus = mplus

I'm not sure how to express the "Monad is a monoid in the category of endofunctors" formulation in Haskell offhand, however.

like image 179
J. Abrahamson Avatar answered Oct 15 '22 13:10

J. Abrahamson


I'm turning my comment into an answer at Tikhon's request. This blog post shows how to unify Monad and Monoid under the same type class using kind polymorphism. This is slightly different from Tel's answer in that the monad is implemented as a monoid in the category of endofunctors, rather than a monoid in a Kleisli category.

like image 36
Gabriella Gonzalez Avatar answered Oct 15 '22 13:10

Gabriella Gonzalez