The default monoid for lists in the GHC Prelude is concatenation.
[1,2,3] <> [4,5,6]
becomes [1,2,3] ++ [4,5,6]
and thus [1,2,3,4,5,6]
I want to write a ZipList Monoid instance that behaves like this:
[
1 <> 4
, 2 <> 5
, 3 <> 6
]
The result is [5,7,9]
assuming I am using the sum monoid.
Note this behaves like zipWith (+)
Potentially it would behave like this:
[
Sum 1 <> Sum 4
, Sum 2 <> Sum 5
, Sum 3 <> Sum 6
]
I need to create a newtype around the ZipList
newtype and the Sum
newtype in order to create an instance for Monoid
, Arbitrary
, and EqProp
.
Thus avoiding orphan instances.
This is how both the ZipList
and the Sum
looks like in the Prelude
:
newtype ZipList a = ZipList { getZipList :: [a] }
newtype Sum a = Sum { getSum :: a }
This is how my newtype MyZipList
looks: Does it look right?
newtype MyZipList a =
MyZipList (ZipList [a])
deriving (Eq, Show)
instance Monoid a => Monoid (MyZipList a) where
mempty = MyZipList (ZipList [])
mappend (MyZipList z) (MyZipList z') =
MyZipList $ liftA2 mappend z z'
instance Arbitrary a => Arbitrary (MyZipList a) where
arbitrary = MyZipList <$> arbitrary
instance Eq a => EqProp (MyZipList a) where
(=-=) = eq
This is how my newtypeMySum
looks like:
Does this look right?
newtype MySum a =
MySum (Sum a)
deriving (Eq, Show)
instance (Num a, Monoid a) => Monoid (MySum a) where
mempty = MySum mempty
mappend (MySum s) (MySum s') = MySum $ s <> s'
instance Arbitrary a => Arbitrary (MySum a) where
arbitrary = MySum <$> arbitrary
I would like assistance in finding out where I went wrong.
x <> mempty == mempty <> x == x
(that is one of the properties of a monoid), in your casemempty <> x == mempty
. I think in case of aZipList
, themappend
should be equal to an infinite list ofmempty
s (of thea
type). – Willem Van OnsemZipList a
? – Dominique DevrieseMySum
to behave exactly likeSum
then that at least looks right. Although I'm not sure why you're wrappingSum
andZipList
if you're going to re-implement their behaviour anyway - you might as well just buildMySum
andMyZipList
directly. That being said, you said you want assistance but you didn't actually say what your problem was. You explained pretty well what you actually did, but your question is missing a description of what's actually going wrong. – Cubic