-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclasses.hs
More file actions
89 lines (61 loc) · 1.94 KB
/
classes.hs
File metadata and controls
89 lines (61 loc) · 1.94 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
79
80
81
82
83
84
85
86
87
88
-- 只需要声明类型类中的函数类型
-- class Eq a where
-- (==) :: a -> a -> Bool
-- (/=) :: a -> a -> Bool
-- x == y = not ( x /= y )
-- x /= y = not ( x == y )
import Tree
data TrafficLight = Red | Yellow | Green
instance Eq TrafficLight where
Red == Red = True
Green == Green = True
Yellow == Yellow = True
_ == _ = False
instance Show TrafficLight where
show Red = "Red light"
show Yellow = "Yellow light"
show Green = "Green light"
-- instance (Eq m) => Eq (Maybe m) where
-- Just x == Just y = x == y
-- Nothing == Nothing = True
-- _ == _ = False
class YesNo a where
yesno :: a -> Bool
instance YesNo Int where
yesno 0 = False
yesno _ = True
instance YesNo [a] where
yesno [] = False
yesno _ = True
instance YesNo Bool where
yesno = id
instance YesNo (Maybe a) where
yesno (Just _) = True
yesno Nothing = False
instance YesNo TrafficLight where
yesno Red = False
yesno _ = True
yesnoIf :: (YesNo y) => y -> a -> a -> a
yesnoIf yesnoVal yesResult noResult = if yesno yesnoVal then yesResult else noResult
-- class Functor f where
-- fmap :: (a -> b) -> f a -> f b
-- instance Functor [] where
-- fmap = map
-- instance Functor Maybe where
-- fmap f (Just x) = Just (f x)
-- fmap f Nothing = Nothing
instance Functor Tree where
fmap f EmptyTree = EmptyTree
fmap f (Node x leftsub rightsub) = Node (f x) (fmap f leftsub) (fmap f rightsub)
-- data Either a b = Left a | Right b
-- instance Functor (Either a) where
-- fmap f (Right x) = Right (f x)
-- fmap f (Left x) = Left x
class Tofu t where
tofu :: j a -> t a j
data Frank a b = Frank {frankField :: b a} deriving (Show)
instance Tofu Frank where
tofu x = Frank x
data Barry t k p = Barry {yabba :: p, dabba :: t k} deriving (Eq, Show)
instance Functor (Barry a b) where
fmap f (Barry {yabba = x, dabba = y}) = Barry {yabba = f x, dabba = y}