aboutsummaryrefslogtreecommitdiff
path: root/Haskell-book/18/Instance/src/List.hs
blob: bd3a06bf66fd30410d06ffb2c3d33d4e27a04a08 (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
39
40
41
42
43
44
module List where

import Test.QuickCheck
import Test.QuickCheck.Checkers

data List a =
    Nil
  | Cons a (List a)
  deriving (Eq, Show)

instance Functor List where
    fmap f Nil = Nil
    fmap f (Cons x xs) = Cons (f x) (fmap f xs)

append :: List a -> List a -> List a
append Nil ys = ys
append (Cons x xs) ys = Cons x $ xs `append` ys

fold :: (a -> b -> b) -> b -> List a -> b
fold _ b Nil = b
fold f b (Cons h t) = f h (fold f b t)

concat' :: List (List a) -> List a
concat' = fold append Nil

flatMap :: (a -> List b) -> List a -> List b
flatMap f as = concat' $ fmap f as

instance Applicative List where
    pure f = Cons f Nil
    Nil <*> _ = Nil
    _ <*> Nil = Nil
    f <*> x = flatMap (\f' -> fmap f' x) f

instance Monad List where
    return = pure
    x >>= f = concat' $ fmap f x

instance Arbitrary a => Arbitrary (List a) where
    arbitrary = frequency [(1, pure Nil),
                           (5, Cons <$> arbitrary <*> arbitrary)]

instance Eq a => EqProp (List a) where
    (=-=) = eq