Skip to content

Instantly share code, notes, and snippets.

@shigemk2
Created August 19, 2015 12:39
Show Gist options
  • Save shigemk2/846ea7b20c3930df300b to your computer and use it in GitHub Desktop.
Save shigemk2/846ea7b20c3930df300b to your computer and use it in GitHub Desktop.
import Data.Monoid
import qualified Data.Foldable as F
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show)
instance F.Foldable Tree where
foldMap f EmptyTree = mempty
foldMap f (Node x l r) = F.foldMap f l `mappend`
f x `mappend`
F.foldMap f r
testTree = Node 5
(Node 3
(Node 1 EmptyTree EmptyTree)
(Node 6 EmptyTree EmptyTree)
)
(Node 9
(Node 8 EmptyTree EmptyTree)
(Node 10 EmptyTree EmptyTree)
)
main = do
print $ F.foldr (+) 0 testTree
print $ F.foldl (*) 1 testTree
print $ getAny $ F.foldMap ( \ x -> Any $ x == 3) testTree
print $ getAny $ F.foldMap ( \ x -> Any $ x > 15) testTree
print $ F.foldMap ( \ x -> [x]) testTree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment