Haskell语言学习笔记(14)Foldable

Haskell语言学习笔记(14)FoldableFoldable Foldable 可折叠 是个类型类 它是 fold 这个函数一般化的结果 class Foldable t where fold Monoid m gt t m gt m fold foldMap id foldMap Monoid m gt a gt

大家好,我是讯享网,很高兴认识大家。

Foldable

Foldable(可折叠)是个类型类,它是 fold 这个函数一般化的结果。
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 -> a 

讯享网

Foldable Tree

讯享网import qualified Data.Foldable as F import Data.Monoid data 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 <> f x <> 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 {- 42 64800 True False [1,3,6,5,8,9,10] 7 10 1 True False -}

traverse_ for_ mapM_ forM_ sequenceA_ sequence_ 函数

traverse_ :: (Foldable t, Applicative f) => (a -> f b) -> t a -> f () traverse_ f = foldr ((*>) . f) (pure ()) for_ :: (Foldable t, Applicative f) => t a -> (a -> f b) -> f () for_ = flip traverse_ mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m () mapM_ f= foldr ((>>) . f) (return ()) forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m () forM_ = flip mapM_ sequenceA_ :: (Foldable t, Applicative f) => t (f a) -> f () sequenceA_ = foldr (*>) (pure ()) sequence_ :: (Foldable t, Monad m) => t (m a) -> m () sequence_ = foldr (>>) (return ()) 
讯享网Prelude> mapM_ putStrLn [show x ++ "*" ++ show y ++ "=" ++ show (x*y) | x <- [1..9], y <- [1..9]] 1*1=1 1*2=2 ... ... 9*8=72 9*9=81 Prelude Data.Foldable> forM_ [1,2,3,4] print 1 2 3 4 Prelude Data.Foldable> sequence_ [print 3, print 4] 3 4 
小讯
上一篇 2025-03-02 17:17
下一篇 2025-01-07 21:35

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/69523.html