13

我编写了一个解析器,如下所示:

class LogParser extends JavaTokenParsers {

  def invertedIndex: Parser[Array[Array[(Int, Int)]]] = {
    num ~> num ~> num ~> rep(postingsList) ^^ {
      _.toArray
    }
  }

  def postingsList: Parser[Array[(Int, Int)]] = {
    num ~> rep(entry) ^^ {
      _.toArray
    }
  }

  def entry = {
    num ~ "," ~ num ^^ {
      case docID ~ "," ~ count => (docID.toInt, count.toInt)
    }
  }

  def num = wholeNumber ^^ (_.toInt)

}

如果我使用 FileReader 从(270MB)文件中解析如下:

val index = parseAll(invertedIndex, new FileReader("path/to/file")).get

我得到一个Exception in thread "main" java.lang.StackOverflowError(我也尝试过包装在 a 中BufferedReader),但我可以通过首先将文件读入 String 来修复它,如下所示:

val input = io.Source.fromFile("path/to/file")
val str = input.mkString
input.close()
val index = parseAll(invertedIndex, str).get

为什么会这样?有什么办法可以避免先将它作为字符串读取,这似乎是一种浪费?

4

1 回答 1

1

还有另一个库 [1] 很像支持 Trampolining 的 scala 解析器组合器,这是您停止 stackoverflow 错误所需要的。

[1] https://github.com/djspiewak/gll-combinators

于 2012-11-16T02:14:01.607 回答