如何在haskell中执行复杂的算术计算?
示例:
eval numb(1) = 1
eval (add(numb(1),numb(2))) = 3
eval (add(mult(numb(1),numb(2)),diff(numb(3),numb(4)))) = 1
答案 0 :(得分:1)
就像那样,但是有一些轻微的语法调整,所以你说的是GHC的语言。
data Expr = Numb Int | Add Expr Expr | Diff Expr Expr | Mult Expr Expr
eval :: Expr -> Int
eval (Numb x) = x
eval (Add e e') = eval e + eval e'
eval (Diff e e') = eval e - eval e'
eval (Mult e e') = eval e * eval e'
在ghci:
> eval (Numb 1)
1
> eval (Add (Numb 1) (Numb 2))
3
> eval (Add (Mult (Numb 1) (Numb 2)) (Diff (Numb 3) (Numb 4)))
1