Skip to content

Instantly share code, notes, and snippets.

@naoto-ogawa
Created May 3, 2017 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naoto-ogawa/4d014ee16dcb0bd9f459c3e82eb8c549 to your computer and use it in GitHub Desktop.
Save naoto-ogawa/4d014ee16dcb0bd9f459c3e82eb8c549 to your computer and use it in GitHub Desktop.
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