0

以下是sbt run我在此清单 [3.5] 上运行时收到的错误[1]

import util.parsing.combinator.JavaTokenParsers

trait ArithParser extends JavaTokenParsers {
    type T
    def expr: Parser[T] = chainl1(term,   "+" ^^^ Add |  "-" ^^^ Sub)
    def term            = chainl1(factor, "*" ^^^ Mul |  "/" ^^^ Div)
    def factor          = floatingPointNumber  ^^ Num | "(" ~> expr <~ ")"

    def Add = (T,T)  => T
    def Sub = (T,T)  => T
    def Mul = (T,T)  => T
    def Div = (T,T)  => T
    def Num = String => T
}

trait DirectEvaluation {
    type T = Double
    val Add = (_: Double) + (_:Double)
    val Sub = (_: Double) - (_:Double)
    val Mul = (_: Double) * (_:Double)
    val Div = (_: Double) / (_:Double)
    val Num = (_: String).toDouble
}

trait ASTBuilding {
    type T = Expr
    sealed abstract class Expr

    case class Add(e1: Expr, e2: Expr) extends Expr
    case class Sub(e1: Expr, e2: Expr) extends Expr
    case class Mul(e1: Expr, e2: Expr) extends Expr
    case class Div(e1: Expr, e2: Expr) extends Expr
    case class Num(e: String) extends Expr
}

object Interpreter extends ArithParser with DirectEvaluation
object Compiler extends ArithParser with ASTBuilding

object Main extends ArithParser {
    def main(args: Array[String]) {
        val defArgs = if (args.isEmpty) Array("10.5 - 4*2") else args
        val parser: ArithParser = if(defArgs.head === "eval") {
                println("Interpreter!"); Interpreter
            } else {
                println("Compiler!"); Compiler
            }
        defArgs.tail foreach {arg =>
            println("Input: " + arg)
            println("Output: " + parseAll(parser.expr, arg))
        }
    }
}

[1] E. Labun,“Scala 中的组合器解析”,Technische Hochschule Mittelhessen,2012 年。

如何修复这些错误?

4

1 回答 1

1

(T,T) => T类型注释,因此您必须将 替换=:

def Add: (T,T) => T

这也正是您所指的论文中的情况。

列表中===也不存在 ,它只是一个==.

你必须调用parseAll解析器:

parser.parseAll(...)

在我看来,您缺少 scala 编程的基础知识,否则您可以自己轻松修复这些错误。我的建议是,在开始学习高级主题之前,请阅读一本好的 scala 书籍以对语言有基本的了解。

于 2013-09-11T06:03:14.893 回答