summaryrefslogtreecommitdiff
path: root/Haskell-book/20/Exercises.hs
blob: 6bab5804fe5019af219b693d99908b8dd86ea328 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
module Exercises where

-- 1
data Constant a b = Constant b deriving (Show)

instance Foldable (Constant a) where
    foldr f acc (Constant x) = f x acc

-- 2
data Two a b = Two a b deriving (Show)

instance Foldable (Two a) where
    foldr f acc (Two _ x) = f x acc

-- 3
data Three a b c = Three a b c deriving (Show)

instance Foldable (Three a b) where
    foldr f acc (Three _ _ x) = f x acc

-- 4
data Three' a b = Three' a b b deriving (Show)

instance Foldable (Three' a) where
    foldr f acc (Three' _ x y) = f y $ f x acc

-- 5
data Four' a b = Four' a b b b deriving (Show)

instance Foldable (Four' a) where
    foldr f acc (Four' _ x y z) = f z $ f y $ f x acc

filterF :: ( Applicative f
           , Foldable t
           , Monoid (f a))
        => (a -> Bool) -> t a -> f a
filterF f x = foldMap y x
    where y k = if f k then pure k else mempty