summaryrefslogtreecommitdiff
path: root/Haskell-book/17/ListApplicative/src/List.hs
blob: 92cf8b93ab92010867b92a3bcdaeb04535b80e8e (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
45
46
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 _ Nil = Nil
    fmap f (Cons x y) = Cons (f x) (fmap f y)

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

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

append' :: List a -> a -> List a
append' acc x = Cons x acc

fromList :: [a] -> List a
fromList xs = foldl (\l a -> Cons a l) Nil xs

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

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