Bifoldable
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
Either is bifoldable.
instance Bifoldable Either where bifoldMap f _ (Left a) = f a bifoldMap _ g (Right b) = g b
(,) is bifoldable
instance Bifoldable (,) where bifoldMap f g ~(a, b) = f a `mappend` g b
Const is bifoldable
instance Bifoldable Const where bifoldMap f _ (Const a) = f a
Application bifoldable
Prelude Data.Bifoldable> bifoldr (^) (-) 2 (Left 2)4Prelude Data.Bifoldable> bifoldr (^) (-) 2 (Right 3)1Prelude Data.Bifoldable> bifoldr (^) (-) 2 (2,3)2Prelude Data.Bifoldable Control.Applicative> bifoldr (^) (-) 2 (Const 2)4Prelude Data.Bifoldable> bifoldl (^) (-) 4 (Left 2)16Prelude Data.Bifoldable> bifoldl (^) (-) 4 (Right 3)1Prelude Data.Bifoldable> bifoldl (^) (-) 4 (2,3)13Prelude Data.Bifoldable Control.Applicative> bifoldl (^) (-) 4 (Const 2)16
Manual calculation
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) = 4bifoldl (^) (-) 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
Haskell Language Learning notes (bifoldable)