Cont as Monoid
David Menendez
zednenem at psualum.com
Sun Sep 23 01:56:58 EDT 2007
On 9/21/07, Iavor Diatchki <iavor.diatchki at gmail.com> wrote:
> Hi,
>
> On 9/18/07, Benjamin Franksen <benjamin.franksen at bessy.de> wrote:
> > Ashley Yakeley wrote:
> > > Monoid ought to be a type, in my view. And each of those wrapper classes
> > > can be replaced by a value in that type.
> >
> > Would you care to elaborate this idea? Do you mean a record with two
> > functions?
>
> Here is how you can do that:
>
> data Monoid a = Monoid { mempty :: a, mappend :: a -> a -> a }
Alternatively,
class Monoid a where
type Carrier a
mempty :: a -> Carrier a
mappend :: a -> Carrier a -> Carrier a -> Carrier a
data Sum a
instance Num a => Monoid (Sum a) where
type Carrier (Sum a) = a
mempty _ = 0
mappend _ = (+)
data Lift f a
instance (Monoid a, Applicative f) => Monoid (Lift f a) where
type Carrier (Lift f a) = f (Carrier a)
mempty _ = pure (mempty (undefined::a))
mappend _ = liftA2 (mappend (undefined::a))
data Writer o a = Writer (Carrier o) a
instance (Monoid o) => Monad (Writer o) where
return a = Writer (mempty (undefined::o)) a
(Writer o1 a) >>= f =
let Writer o2 b = f a in Writer (mappend (undefined::o) o1 o2) b
--
Dave Menendez <dave at zednenem.com>
<http://www.eyrie.org/~zednenem/>
More information about the Libraries
mailing list