Haskell Language Learning notes (bifoldable)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.