Haskell笔记(5)

–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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值