如何简化基本的算术表达式?
例如:
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 (Plus a b) = case (simplify a, simplify b) of (Const ca, Const cb) -> Const (ca + cb)
等等。或者,你可以使用镜头rewrite
组合器来对一个固定点进行相同的操作。 - Edward Kmett