Haskell Foldable tree mempty implementation

76 Views Asked by At

Hi I need help in understanding this Foldable tree implementation from from here

Consider the following

import qualified Data.Foldable as F  

data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)  

instance F.Foldable Tree where  
    foldMap f Empty = mempty   
    foldMap f (Node x l r) = F.foldMap f l `mappend`  
                             f x           `mappend`  
                             F.foldMap f r  

I have difficulty in understanding how in this example, mempty and mappend get their implementation what their types and how they infered from for example the following invokation.

F.foldl (+) 0 testTree 

Thanks

1

There are 1 best solutions below

2
Fyodor Soikin On

Check out the signature of foldMap:

foldMap :: Monoid m => (a -> m) -> t a -> m

See the Monoid m => constraint in there? It means that every time somebody calls foldMap, they have to choose a type m and provide an instance of Monoid for that type.

It's from that instance that mempty and mappend are coming. Since foldMap has been provided an instance of Monoid, it can call methods from that instance.