标签:mon const pre down 学习笔记 haskell 语言 mem lda
class Bifoldable p where
bifold :: Monoid m => p m m -> m
bifold = bifoldMap id id
bifoldMap :: Monoid m => (a -> m) -> (b -> m) -> p a b -> m
bifoldMap f g = bifoldr (mappend . f) (mappend . g) mempty
bifoldr :: (a -> c -> c) -> (b -> c -> c) -> c -> p a b -> c
bifoldr f g z t = appEndo (bifoldMap (Endo #. f) (Endo #. g) t) z
bifoldl :: (c -> a -> c) -> (c -> b -> c) -> c -> p a b -> c
bifoldl f g z t = appEndo (getDual (bifoldMap (Dual . Endo . flip f) (Dual . Endo . flip g) t)) z
instance Bifoldable Either where
bifoldMap f _ (Left a) = f a
bifoldMap _ g (Right b) = g b
instance Bifoldable (,) where
bifoldMap f g ~(a, b) = f a `mappend` g b
instance Bifoldable Const where
bifoldMap f _ (Const a) = f a
Prelude Data.Bifoldable> bifoldr (^) (-) 2 (Left 2)
4
Prelude Data.Bifoldable> bifoldr (^) (-) 2 (Right 3)
1
Prelude Data.Bifoldable> bifoldr (^) (-) 2 (2,3)
2
Prelude Data.Bifoldable Control.Applicative> bifoldr (^) (-) 2 (Const 2)
4
Prelude Data.Bifoldable> bifoldl (^) (-) 4 (Left 2)
16
Prelude Data.Bifoldable> bifoldl (^) (-) 4 (Right 3)
1
Prelude Data.Bifoldable> bifoldl (^) (-) 4 (2,3)
13
Prelude Data.Bifoldable Control.Applicative> bifoldl (^) (-) 4 (Const 2)
16
bifoldr (^) (-) 1 (2,3)
= appEndo (bifoldMap (Endo #. (^)) (Endo #. (-)) (2,3)) 1
= appEndo ((Endo #. (^) $ 2) (Endo #. (-) $ 3)) 1
= appEndo ((Endo (2^)) `mappend` (Endo (3-))) $ 1
= (2^) . (3-) $ 1
= 2 ^ (3 - 1) = 4
bifoldl (^) (-) 4 (2,3)
= appEndo (getDual (bifoldMap (Dual . Endo . flip (^)) (Dual . Endo . flip (-)) (2,3))) 4
= appEndo (getDual ((Dual . Endo . flip (^) $ 2) `mappend` (Dual . Endo . flip (-) $ 3))) 4
= appEndo (getDual ((Dual $ Endo (^2)) `mappend` (Dual $ Endo (subtract 3)))) 4
= (subtract 3) . (^2) $ 4
= (4 ^ 2) - 3 = 13
标签:mon const pre down 学习笔记 haskell 语言 mem lda
原文地址:http://www.cnblogs.com/zwvista/p/8016224.html