–Eq, Ord, Show, Read, Num
–Data Bool = True | False
–表示自然数
思路:1,0是自然数
2.如果n是自然数,则n+1是自然数
data Nat = Zero | Sue Nat –deriving Show
instance Show Nat where
show n = show (nat2Int n)
nat2Int :: Nat -> Nat
nat2Int Zero = 0
nat2Int (Suc n) = 1 + nat2Int n
–计算自然数加法
add :: Nat -> Nat -> Nat
add Zero n = n
add (Suc m) n = Suc (add m n)
–描述表达式(如2 * 3 + 4)
–an Int is an expression
–an varible is an expression
–if e1 and e2 are experessions, then either (e1 + e2) or (e1 * e2) is an expression.
data Exp = Val Int | Add Exp Exp | Mul Exp Exp | var String(增加了变量计算 –deriving show
–Val 2 <==> 2, Add ( Val 2) (Val 3) <==> 2 + 3
实现:
eval :: Exp -> [(String, Int)] -> Int –[(String, Int)]替换
eval (Val n) _ = n
eval (Add e1 e2 subs) = (eval e1 subs) + (eval e2 subs)
eval (Mul e1 e2 subs) = (eval e1 subs) * (eval e2 subs)
eval (Var x) subs = head [k | (y, k) <- subs, y == x]
subs ::
instance Show Exp where
show e = formatExp e
formatExp (Val n) = show n
formatExp (Add e1 e2) = “(” ++ formatExp e1 ++ “+” ++ formatExp e2 ++ “)” –会有多余的括号
formatExp (Mul e1 e2) = formatExp e1 ++ “*” ++ formatExp e2
formatExp (Var x) = x