overloaded重载,使定义的函数满足多个Instance,当调用函数时自动找符合的instance
(出现类型约束的,都是重载函数)
class Eq a where
(==) :: a -> a -> Bool (这些都是instance)
(/=) :: a -> a -> Bool
(/=) x y = not (x == y)
class Num a where
(+) :: a -> a -> a
negate :: a -> a
1.自定义一个class
class Sizable a where
size :: a -> Int
instance Sizable Int where
size :: Int -> Int
size x = x
instance Sizable Bool where
size :: Bool -> Int
size True = 1
size False = 0
instance Sizable Integer where
size :: Integer -> Int
size x = fromInteger x
instance Sizable [a] where
size :: [a] -> Int
size xs = sum (map size xs)
hasSize :: Sizable a => a -> Int
hasSize x = size x
可以代替{-
hasSize1 :: Int -> Int
hasSize1 x = x
hasSize2 :: Bool -> Int
hasSize2 True = 1
hasSize2 False = 0
hasSize3 :: Integer -> Int
hasSize3 x = fromInteger x
-}
2.自定义一个类型(data types),表示一年四季
data Bool = True | False (两者中的一个)
data People = Age Sex Name (三者都包含)
data Season = Spring | Summer | Fall | Winter (自定义类型)
instance Show Season where (为了能够show )
show Spring = “Spring”
show Summer = “Summer”
show Fall = “Fall”
show Winter = “Winter”
自定义show时特别注意格式,data和instance一行,show空两格
instance Eq Season where (为了能够Eq)
Spring == Spring = True
Summer == Summer = True
Fall == Fall = True
Winter == Winter = True
_ == _ = False
isHot :: Season -> Bool
isHot Spring = True
isHot Summer = True
isHot Fall = True
isHot Winter = False
3.type Name = String
自定义一个星期七天
data Week = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday deriving (Show, Eq)
–instance Show Week where
–deriving Show代替(instance Show Week where)将Monday, Tuesday……转换为String类型
derving+ …,可以免除定义
print x = putStr (show x)
定义表示人的类型People,包括姓名,性别和年龄
type Name = String
type Age = Int
type Sex = Man | Woman derving (Show ,Eq)
data People = Person Name Sex Age (Person 这些是构造符)
instance Show People where show
(Person name sex age) = name ++ “,” ++ show sex ++ show age
对于[a]
data List a = Nil | Cons a (List a)
–举几个例子,Nil, Cons x Nil , Cons x (Cons x Nil)
instance Show a =>Show (List a) where
show Nil = “[]”
show (Cons x xs) = show x ++ “:” ++ show xs
电话号码本
type PhoneNumber = String
type PhoneBook = [(Name,PhoneNumber)]
data Maybe a = Nothing | Just a
data Ordering = LT | EQ | GT
(LT 即less than ,GT即great than)
lookUp :: PhoneBook -> Name -> PhoneNumber
lookUp [] name = (根据otherwise推下去发现缺少递归基)
lookUp ((n,p) : ps) name
| n == name = p
| otherwise = lookUp ps name
myPhoneBook = [(“Gao”,”1232”),(“Wang”,”2323”)]
给定表达式,如2,2+2,2*3,7*4+2,计算值
data Expr = Num Int | Add Expr Expr | Mul Expr Expr
–instance Show
–instance Eq Expr
–2即Num 2 , 2+2即 Add (Num 2) (Num 2) , 2*3即Mul (Num 2) (Num 3) , 7*4+2即Add (Mul (Num 4) (Num 7) ) (Num 2)
eval :: Expr ->Int
eval (Num n) = n
eval (Add e1 e2) = (eval e1) + (eval e2)
eval (Mul e1 e2) = (eval e1) * (eval e2)