-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathch11.hs
More file actions
78 lines (54 loc) · 1.8 KB
/
Copy pathch11.hs
File metadata and controls
78 lines (54 loc) · 1.8 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
module Ch11 where
-- newtype can have only a single unary constructor
-- newtype has no runtime overhead; it reuses the representation of the type it contains
-- the difference between newtype and its type is gone after compilation
-- with newtype, we can define different typeclasses, as the original type
data Price = Price Integer deriving (Eq, Show)
data Size = Size Integer deriving (Eq, Show)
data Manufacturer = Mini | Mazda | Tata deriving (Eq, Show)
data Airline = PapuAir | CataputsR'Us | TakeYourChancesUnited deriving (Eq, Show)
data Vehicle = Car Manufacturer Price
| Plane Airline Size
deriving (Eq, Show)
myCar :: Vehicle
myCar = Car Mini (Price 14000)
urCar :: Vehicle
urCar = Car Mazda (Price 20000)
clownCar :: Vehicle
clownCar = Car Tata (Price 7000)
doge :: Vehicle
doge = Plane PapuAir (Size 50)
isCar :: Vehicle -> Bool
isCar (Car _ _) = True
isCar _ = False
isPlane :: Vehicle -> Bool
isPlane (Plane _ _) = True
isPlane _ = False
areCars :: [Vehicle] -> [Bool]
areCars = map isCar
getManu :: Vehicle -> Manufacturer
getManu (Car manu _) = manu
getManu _ = Mini
newtype Goats = Goats Int deriving (Eq, Show)
newtype Cows = Cows Int deriving (Eq, Show)
class TooMany a where
tooMany :: a -> Bool
instance TooMany Int where
tooMany n = n > 42
newtype Cats =
Cats Int deriving (Eq, Show, Num)
instance TooMany Cats where
tooMany (Cats n) = n > 5
instance TooMany (Int, String) where
tooMany (n, _) = n > 10
-- instance TooMany (Int, Int) where
-- tooMany (x, y) = x + y > 11
instance (Num a, TooMany a) => TooMany (a, a) where
tooMany (x, y) = tooMany (x + y)
--
-- tooManyGoats :: Int -> Bool
-- tooManyGoats n = n > 5
tooManyGoats :: Goats -> Bool
tooManyGoats (Goats n) = n > 5