sealed trait Expression
case class Lit(value: Int) extends Expression
case class Add(expr1: Expression, expr2: Expression) extends Expression
case class Mult(expr1: Expression, expr2: Expression) extends Expression
def simplify(expr: Expression): Expression = expr match {
case Add(Mult(a, b), Mult(a1, c)) if a == a1 => Mult(a, Add(b, c))
case _ => expr
}
但是如何以OOP的方式轻松地实现它呢?
sealed trait Expression {
def simplify: Expression
}
case class Lit(value: Int) extends Expression {
override def simplify: Expression = ???
}
case class Add(expr1: Expression, expr2: Expression) extends Expression {
override def simplify: Expression = ???
}
case class Mult(expr1: Expression, expr2: Expression) extends Expression {
override def simplify: Expression = ???
}
1条答案
按热度按时间qfe3c7zg1#
我猜他们的意思是,这个规则可以很容易地在FP中通过使用嵌套模式的模式匹配来实现
但是如何以OOP的方式轻松地实现它呢?
实际上,它可以使用visitor pattern(double/multiple调度,模拟多方法)来实现
或
如果我们想让
simplify
递归呢?