Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
a sample of deriving foldable

DeriveFoldable

Prelude> :set -XDeriveFoldable
Prelude>
Prelude> -- DeriveFoldable needs Functor !!
Prelude>
Prelude> data Foo a b = Leaf b | Branch [Foo a b] deriving (Show, Foldable)

<interactive>:1:58: error:
     Can't make a derived instance of Foldable (Foo a)’:
        You need DeriveFoldable to derive an instance for this class
     In the data declaration for Foo
Prelude>
Prelude> data Foo a b = Leaf b | Branch [Foo a b] deriving (Show, Foldable, Functor)
Prelude> --         ^        ^                 ^
Prelude> --         +--------+-----------------+--------------> focus
Prelude>
Prelude> Branch [Leaf 2, Leaf 3, Branch [Leaf 4, Leaf 5]]
Branch [Leaf 2,Leaf 3,Branch [Leaf 4,Leaf 5]]
Prelude>
Prelude> -- foldr
Prelude>
Prelude> foldr (+) 0 $ Branch [Leaf 2, Leaf 3, Branch [Leaf 4, Leaf 5]]
14

Prelude>
Prelude> -- foldMap (1) ; When we already have monoid instances, 'id' function is enough.
Prelude>
Prelude> :m Data.Monoid
Prelude Data.Monoid> foldMap (id) $ Branch [Leaf (Sum 2), Leaf (Sum 3), Branch [Leaf (Sum 4), Leaf (Sum 5)]]
Sum {getSum = 14}

Prelude>
Prelude> -- foldMap (2) ; When we don't have monoid instances, we meke them.
Prelude>
Prelude Data.Monoid>  foldMap Sum $ Branch [Leaf 2, Leaf 3, Branch [Leaf 4, Leaf 5]]
Sum {getSum = 14}
Prelude Data.Monoid> :t Sum
Sum :: a -> Sum a

Prelude Data.Monoid>
Prelude Data.Monoid> -- We have fmap as usual.
Prelude Data.Monoid>
Prelude Data.Monoid> fmap (+1) $ Branch [Leaf 2, Leaf 3, Branch [Leaf 4, Leaf 5]]
Branch [Leaf 3,Leaf 4,Branch [Leaf 5,Leaf 6]]
Prelude Data.Monoid>

Prelude>
Prelude> -- focus is the last parameter.
Prelude>
Prelude> data Foo a b = Leaf a | Branch [Foo a b] deriving (Show, Foldable, Functor)
Prelude> --         ^        ?                 ^
Prelude> --         +--------+-----------------+--------------> focus
Prelude>
Prelude> fmap (+1) $ Branch [Leaf 2, Leaf 3, Branch [Leaf 4, Leaf 5]]
Branch [Leaf 2,Leaf 3,Branch [Leaf 4,Leaf 5]]
Prelude>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment