Skip to content

Instantly share code, notes, and snippets.

@tonymorris
Forked from gregberns/main.hs
Created July 2, 2021 06:54
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 tonymorris/91cb08a0fcaec2cd4f29372deb52bec3 to your computer and use it in GitHub Desktop.
Save tonymorris/91cb08a0fcaec2cd4f29372deb52bec3 to your computer and use it in GitHub Desktop.
How to make a Foldable Instance with multiple parameters
import Data.Monoid
-- This code doesn't work...
-- How can you make a multi-parameter data type be Foldable?
-- foldMap over `a` so it can be converted to a Monoid
data BinaryTree3 a v
= Node3 a (BinaryTree3 a v) (BinaryTree3 a v)
| Leaf3 a v
deriving (Show)
instance Foldable (BinaryTree3 a) where
-- foldMap :: Monoid m => (a -> m) -> t a -> m
-- foldMap :: Monoid m => (a -> m) -> BinaryTree3 a v -> m
foldMap f (Node3 a l r) = foldMap f l `mappend` foldMap f r
foldMap f (Leaf3 a v) = f v
leaf1 = Leaf3 False (1::Int)
f1 = foldMap (\a -> Sum a) leaf1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment