
I have a question related to using Writer with a user defined datatype where I want some of the fields to append and others to just take the last value as a reduced example, if I had a data type like this: data Mydat = Mydat {list1 :: [String], item1 :: Float} and I wanted a Writer MyDat a where the strings keep on appending, but the float value just takes the last value. would I have to define Float as an instance of Monoid like instance Monoid Float where mempty = 0.0 mappend a b = a ?or maybe mappend a b = b before defining an instance of MyDat 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? Thank you, Britt

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

On Tue, Mar 15, 2011 at 9:42 PM, Isaac Dupree < ml@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)
participants (3)
-
Britt Anderson
-
Daniel Fischer
-
Isaac Dupree