Haskell 中的复杂算术表达式
Complex Arithmetic Expression in Haskell
如何在 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
差不多就是这样,但稍微调整了一些语法,所以您说的是 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
如何在 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
差不多就是这样,但稍微调整了一些语法,所以您说的是 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