I'm trying to write functions that add and multiply all elements in a list using monoids and Foldable. I've set up some code that I think works:
data Rose a = a :> [Rose a]
deriving (Eq, Show)
instance Functor Rose where
fmap f rose@(a:>b) = (f a :> map (fmap f) b)
class Monoid a where
mempty :: a
(<>) :: a -> a -> a
instance Monoid [a] where
mempty = []
(<>) = (++)
newtype Sum a = Sum { unSum :: a } deriving (Eq, Show)
newtype Product a = Product { unProduct :: a } deriving (Eq, Show)
instance Num a => Monoid (Sum a) where
mempty = Sum 0
Sum n1 <> Sum n2 = Sum (n1 + n2)
instance Num a => Monoid (Product a) where
mempty = Product 1
Product n1 <> Product n2 = Product (n1 * n2)
class Functor f => Foldable f where
fold :: Monoid m => f m -> m
foldMap :: Monoid m => (a -> m) -> f a -> m
foldMap f a = fold (fmap f a)
instance Foldable [] where
fold = foldr (<>) mempty
instance Foldable Rose where
fold (a:>[]) = a <> mempty
fold (a:>b) = a <> (fold (map fold b))
And then after having defined the different Foldable instances and the Sum and Product types I want to define two functions that add respectively multiply the elements in a datastructure, but this gives errors which I do not know how to interpret, I must admit that I it was more guess work than actual logic so a thorough explanation of your answer would be welcome.
fsum, fproduct :: (Foldable f, Num a) => f a -> a
fsum b = foldMap Sum b
fproduct b = foldMap Product b
Error:
Assignment3.hs:68:14: error:
* Occurs check: cannot construct the infinite type: a ~ Sum a
* In the expression: foldMap Sum b
In an equation for `fsum': fsum b = foldMap Sum b
* Relevant bindings include
b :: f a (bound at Assignment3.hs:68:6)
fsum :: f a -> a (bound at Assignment3.hs:68:1)
|
68 | fsum b = foldMap Sum b
| ^^^^^^^^^^^^^
Assignment3.hs:69:14: error:
* Occurs check: cannot construct the infinite type: a ~ Product a
* In the expression: foldMap Product b
In an equation for `fproduct': fproduct b = foldMap Product b
* Relevant bindings include
b :: f a (bound at Assignment3.hs:69:10)
fproduct :: f a -> a (bound at Assignment3.hs:69:1)
|
69 | fproduct b = foldMap Product b
| ^^^^^^^^^^^^^^^^^
If you use Sum
(or Product
) in the foldMap
, you will first map the items in the Foldable
to Sum
s (or Product
s). Therefore the result of fsum
will - like you defined it - be a Sum a
, not an a
:
fsum :: (Foldable f, Num a) => f a -> Sum a
fsum b = foldMap Sum b
In order to retrieve the value that is wrapped in the Sum
constructor, you can fetch it with the unSum :: Sum a -> a
getter:
fsum :: (Foldable f, Num a) => f a -> a
fsum b = unSum (foldMap Sum b)
or after an eta-reduction:
fsum :: (Foldable f, Num a) => f a -> a
fsum = unSum . foldMap Sum
The same should happen for a Product
.