考虑以下Scala案例:(受此blog post启发)
sealed abstract class Expr
case class X() extends Expr
case class Const(value : Int) extends Expr
case class Add(left : Expr, right : Expr) extends Expr
case class Mult(left : Expr, right : Expr) extends Expr
case class Neg(expr : Expr) extends Expr
在Haxe,这会回应:
enum Expr {
X();
Const(val:Int);
Add(left:Expr, right:Expr);
Mult(left:Expr, right:Expr);
Neg(expr:Expr);
}
在两种语言中,为任何类型的嵌套表达式编写eval函数都非常简单。但是我对以下简化函数感兴趣(仅关注乘法):
在scala中:
def simplify(expression: Expr): Expr = expression match {
case Mult(_, Const(0)) => Const(0)
case Mult(Const(0), _) => Const(0)
case Mult(left, Const(1)) => simplify(left)
case Mult(Const(1), right) => simplify(right)
case Mult(Const(leftVal), Const(rightVal)) => Const(leftVal * rightVal)
case Mult(left, right) => Mult(simplify(left),simplify(right))
case Add(left, right) => Add(simplify(left),simplify(right))
case Neg(left) => simplify(left)
case _ => expression
}
我的问题:在Haxe中编写等效内容的最简洁/最简洁的方法是什么? 这些是我的尝试,但我对它们都不太满意。
第一个(有点臃肿):
public static function simplify(expr:Expr):Expr{
switch(expr){
case Mult(left, right):
if(left.enumEq(Const(0)) || right.enumEq(Const(0))) return Const(0);
switch(left){
case Const(leftVal):
if(leftVal == 1) return right.simplify();
switch(right){
case Const(rightVal): return Const(rightVal * leftVal);
default:
}
default:
switch(right){
case Const(rightVal):
if(rightVal == 1) return left.simplify();
default:
}
}
return Mult(left.simplify(), right.simplify());
case Add(left, right): return Add(left.simplify(), right.simplify());
case Neg(expr): return Neg(expr.simplify());
default: return expr;
}
}
另一种尝试(更简洁,但更黑):
public static function simplify(expr:Expr):Expr{
switch(expr){
case Mult(left, right):
if(left.enumEq(Const(0)) || right.enumEq(Const(0))) return Const(0);
if(left.enumEq(Const(1))) return right.simplify();
if(right.enumEq(Const(1))) return left.simplify();
if(left.enumConstructor() == right.enumConstructor() &&
left.enumConstructor() == Const(null).enumConstructor())
return Const(Std.int(left.enumParameters()[0] *
right.enumParameters()[0]));
return Mult(left.simplify(), right.simplify());
case Add(left, right): return Add(left.simplify(), right.simplify());
case Neg(expr): return Neg(expr.simplify());
default: return expr;
}
}
答案 0 :(得分:3)
Haxe目前不支持深度模式匹配。这是3.0版本中实现的内容之一。