如何简化基本算术表达式?
例如
module ExprOps where simplify :: Expr -> Expr simplify (Plus(Var"x") (Const 0)) = Var "x"
我需要做什么?
module Expr where -- Variables are named by strings, assumed to be identifiers. type Variable = String -- Representation of expressions. data Expr = Const Integer | Var Variable | Plus Expr Expr | Minus Expr Expr | Mult Expr Expr deriving (Eq, Show)
我想到的简化是:
0*e = e*0 = 0 1*e = e*1 = 0+e = e+0 = e-0 = e
并且简化常量子表达式,例如Plus(Const 1)(Const 2)将成为Const 3.我不希望连接变量(或变量和常量):Var"st"是Var"s"的不同变量.
我想要实现的是创建一个像上面那样使用被调用函数的模块 simplify :: Expr->Expr
那么,你有正确的通用模型.您只需要更多规则并递归应用简化过程.
simplify :: Expr -> Expr simplify (Mult (Const 0) x) = Const 0 simplify (Mult x (Const 0)) = Const 0 simplify (Plus (Const 0) x) = simplify x simplify (Plus x (Const 0)) = simplify x simplify (Mult (Const 1) x) = simplify x simplify (Mult x (Const 1)) = simplify x simplify (Minus x (Const 0)) = simpify x simplify (Plus (Const x) (Const y)) = Const (x + y) simplify (Minus (Const x) (Const y)) = Const (x - y) simplify (Mult (Const x) (Const y)) = Const (x * y) simplify x = x