2016-04-26 136 views
-1

我写过这个函数,它应该返回表示算术表达式的字符串。将表达式转换为字符串

 import scala.util.parsing.combinator._ 

object ArithEval extends ArithEvalLike { 


def eval (e:Expr):Double = e match { 
    case Num(a) => a 
    case Exponent(a,b) => Math.pow(eval(a),eval(b)) 
    case Add(a,b) =>eval(a) + eval(b) 
    case Sub(a,b) =>eval(a) - eval(b) 
    case Mul(a,b) =>eval(a) * eval(b) 
    case Div(a,b) =>eval(a)/eval(b) 
    } 
} 


object ArithPrinter extends ArithPrinterLike { 
def print (e: Expr): String = e match { 
    case Num(a) => "a" 
    case Exponent(a,b) =>print(a).toString + "^" + print(b).toString 
    case Add(a,b) => print(a).toString + "+" + print(b).toString 
    case Sub(a,b) => print(a).toString + "-" + print(b).toString 
    case Mul(a,b) =>print(a).toString + "*" + print(b).toString 
    case Div(a,b) =>print(a).toString + "/" + print(b).toString 
    } 
} 

这似乎不正确,因为我的一些测试失败。

下面是我跑的测试:

阶> ArithPrinter.print(Mul的(民(2.0),穆尔(添加(民(3.0),序号(5.0)),NUM(-10.0))) )

它说,它无法找到“民”

我不知道这是否是我的测试是错误的或者功能本身。

我在正确的轨道上吗?

+2

什么是失败的测试?你可以发布整个代码吗? –

+0

发布失败的测试代码。 – marcospereira

+0

我们不能说没有'Num','Add'等的定义。如果我说“找不到Num”,可能没有定义Num''或者它是错误的类型 –

回答

0
case Num(a) => "a" 

这看起来不对。你只是在打印字符串“a”。你可能想要a.toString

+0

我改变了但同样的错误发生 – rocketman

+0

你的Num的构造函数是什么?你可能创建了一个需要一个Int但是传递一个float的case类? – Ren