class Foldable t where fold :: Monoid m => t m -> m fold = foldMap id foldMap :: Monoid m => (a -> m) -> t a -> m foldMap f = foldr (mappend . f) mempty foldr :: (a -> b -> b) -> b -> t a -> b foldr' :: (a -> b -> b) -> b -> t a -> b foldl :: (b -> a -> b) -> b -> t a -> b foldl' :: (b -> a -> b) -> b -> t a -> b foldr1 :: (a -> a -> a) -> t a -> a foldl1 :: (a -> a -> a) -> t a -> a toList :: t a -> [a] null :: t a -> Bool length :: t a -> Int elem :: Eq a => a -> t a -> Bool maximum :: forall a . Ord a => t a -> a minimum :: forall a . Ord a => t a -> a sum :: Num a => t a -> a PRoduct :: Num a => t a -> aFoldable Tree
import qualified Data.Foldable as Fimport Data.Monoiddata Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)instance F.Foldable Tree where foldMap f Empty = 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 Empty Empty) (Node 6 Empty Empty) ) (Node 9 (Node 8 Empty Empty) (Node 10 Empty Empty) )main = do -- print $ F.foldl (+) 0 testTree print $ F.sum testTree -- print $ F.foldl (*) 1 testTree print $ F.product 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 print $ F.toList testTree print $ F.length testTree print $ F.maximum testTree print $ F.minimum testTree print $ 3 `F.elem` testTree print $ F.null testTree {-4264800TrueFalse[1,3,6,5,8,9,10]TrueFalse-}
新闻热点
疑难解答