[Haskell-beginners] Writer and mappend

Daniel Fischer daniel.is.fischer at googlemail.com
Tue Mar 15 22:09:35 CET 2011


On Tue, Mar 15, 2011 at 9:42 PM, Isaac Dupree <
ml at isaac.cedarswampstudios.org> wrote:

> On 03/15/11 16:18, Britt Anderson wrote:
>
>> Or can I do something like
>>
>> instance Monoid MyDat where
>> mempty = Mydat [] 0
>> mappend a b = (Mydat (mappend (list1 a) (list1 b)) (item1 a))
>>
>> without defining an instance for Float?
>>
>
> Yes, you can do this.  Try it!  Does it typecheck?  Then there's a large
> chance it's correct!  (In addition to more-philosophical reasons.)
>
> -Isaac


But in this case, it wouldn't really be correct, since mempty wouldn't be a
two-sided neutral element. With the above,

mempty `mappend` (MyDat ["Foo"] 1) = MyDat ["Foo"] 0

For correctness, you could use Data.Monoid.First or Data.Monoid.Last

data MyDat = MyDat [String] (First Float)

instance Monoid MyDat where
  mempty = MyDat mempty mempty
  (MyDat l1 i1) `mappend` (MyDat l1 i2) =
              MyDat (l1 `mappend` l2) (i1 `mappend` i2)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110315/d30e95c2/attachment.htm>


More information about the Beginners mailing list