Skip to content

Instantly share code, notes, and snippets.

@gregberns
Created July 2, 2021 06:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gregberns/f34726094f68ce7cbb87dc66f4817fd8 to your computer and use it in GitHub Desktop.
Save gregberns/f34726094f68ce7cbb87dc66f4817fd8 to your computer and use it in GitHub Desktop.
How to make a Foldable Instance with multiple parameters
-- 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) `mappend` f a
foldMap f (Leaf3 a v) = f a
leaf1 = Leaf3 False (1::Int)
f1 = foldMap (\a -> Any a) leaf1
@gregberns
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment