summaryrefslogtreecommitdiff
path: root/Haskell-book/14/qc/src/UsingQuickCheck.hs
blob: f0fa27fb865dcb2958a008744db8666c78c10243 (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
47
48
49
50
51
52
53
54
55
56
57
58
module UsingQuickCheck where

import Test.QuickCheck

--
-- 1
--
half :: (Eq a, Fractional a) => a -> a
half x = x / 2

halfIdentity :: (Eq a, Fractional a) => a -> a
halfIdentity = (*2) . half

--
-- 2
--
-- for any list you apply sort to
-- this property should hold
listOrdered :: (Ord a) => [a] -> Bool
listOrdered xs =
    snd $ foldr go (Nothing, True) xs
    where go _ status@(_, False) = status
          go y (Nothing, t) = (Just y, t)
          go y (Just x, _) = (Just y, x >= y)

--
-- 3
--
plusAssociative :: (Ord a, Integral a) => a -> a -> a -> Bool
plusAssociative x y z = x + (y + z) == (x + y) + z

plusCommutative :: (Ord a, Integral a) => a -> a -> Bool
plusCommutative x y = x + y == y + x

--
-- 4
--
mulAssociative :: (Ord a, Integral a) => a -> a -> a -> Bool
mulAssociative x y z = x * (y * z) == (x * y) * z

mulCommutative :: (Ord a, Integral a) => a -> a -> Bool
mulCommutative x y = x * y == y * x

data Fool = Fulse
          | Frue
          deriving (Eq, Show)

data Fool' = Fulse' -- 2/3
           | Frue'  -- 1/3
           deriving (Eq, Show)

instance Arbitrary Fool where
    arbitrary = oneof [ return Fulse
                      , return Frue ]

instance Arbitrary Fool' where
    arbitrary = frequency [ (3, return Fulse')
                          , (1, return Frue')]