[Haskell-beginners] Fwd: My first functioning haskell project - a
steganography utility
edgar klerks
edgar.klerks at gmail.com
Tue Jul 13 10:50:51 EDT 2010
Hi Tim,
I am not too deep into category theory. But the Data.Monoid class defines
the identity as mempty. And the binary operation as mappend. So that would
be:
maybePlus = maybe mempty id $ liftM2 (mappend) x y
You only have to define Num as Monoid, because there are more monoids
possible. (Multiplication, addition etc).
That would look something like this:
instance (Num a) => Monoid a where ...
Have a look at the monoid class:
http://haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Data-Monoid.html
Greets,
Edgar
On Tue, Jul 13, 2010 at 4:39 PM, Tim Cowlishaw <tim at timcowlishaw.co.uk>wrote:
> On 13 Jul 2010, at 15:31, edgar klerks wrote:
>
> > You can use maybe from Data.Maybe: b -> (a -> b) -> Maybe a -> b
> >
> > to create your maybe plus function:
> >
> > maybePlus x y = maybe 0 id $ liftM2 (+) x y
> >
> > That is somewhat cleaner.
>
> Aah thanks Edgar - I'd meant to ask about this specifically actually, as
> addition is a monoid over the real numbers and therefore has an identity
> element, I was wondering if there was an easier way to generalise it to cope
> with arguments in the Maybe monad. As far as I can see, this is precisely
> what you describe above. Therefore, would I be right in saying that your
> approach can be generalised to any function which forms a monoid over a
> specific type?
>
> I'm imagining something like:
>
> maybeMonoid :: (a -> a -> a) -> a -> (Maybe a -> Maybe a -> a)
> maybeMonoid f identity = maybe identity id $ liftM2 f
>
> Thanks for the feedback!
>
> Cheers,
>
> Tim
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100713/c4e66b21/attachment-0001.html
More information about the Beginners
mailing list