简体   繁体   English

为什么RegexParsers用“ def”而不是“ lazy val”来定义?

[英]Why are RegexParsers definied with “def” instead of “lazy val”?

In the Scaladoc about RegexParsers , there is the following code: 在有关RegexParsers的Scaladoc中 ,有以下代码:

object Calculator extends RegexParsers {
  def number: Parser[Double] = """\d+(\.\d*)?""".r ^^ { _.toDouble }
  def factor: Parser[Double] = number | "(" ~> expr <~ ")"
...

I don't see why we it's written with a def and not with a val or a lazy val ? 我不明白为什么我们用def而不用vallazy val编写它? I would write like this : 我会这样写:

object Calculator extends RegexParsers {
  lazy val number: Parser[Double] = """\d+(\.\d*)?""".r ^^ { _.toDouble }
  lazy val factor: Parser[Double] = number | "(" ~> expr <~ ")"
...

There is an actual semantic reason for it. 有一个实际的语义原因。 Look at the type signature for Parser : 查看Parser的类型签名:

 abstract class Parser[+T] extends (Input) ⇒ ParseResult[T]

Parser[T] is in fact a function from some abstract kind of Input to a ParseResult[T] . 实际上, Parser[T]是从某种抽象InputParseResult[T]的函数。 In many (probably most) cases this function captures some aspect of the state of the parse being carried out. 在许多(可能是大多数)情况下,此函数捕获正在执行的解析状态的某些方面。 If such a production were captured in a val , (lazy or otherwise) it could not be used in more than one place in a given parse tree. 如果在val中捕获了这种生成(延迟或其他),则不能在给定的解析树中的多个位置中使用它。 The only productions that can be made val are fixed terminals such as punctuation and keywords. val唯一可用的产品是标点符号和关键字之类的固定终端。

Addendum 附录

It has been years since I've worked on Scala combinator parsers and I was comparatively a Scala newbie at the time, so it's entirely possible I was simply mistaken. 自从我从事Scala组合器解析器工作已经有好几年了,那时我还只是一个Scala新手,所以我完全有可能被误解了。 However, my recollection is that that Reader represented not the input as a whole but rather a specific sub-sequence of that input. 但是,我的回忆是, Reader并不代表整个输入,而是代表该输入的特定子序列。 Thus if the production did not have a fixed input sequence, the production could not be a val . 因此,如果生产不具有固定的输入序列,则生产不能为val

I actually do have a little side project that needs a parser, so when I get some time, I can either confirm or refute that understanding. 实际上,我确实有一个需要解析器的小项目,因此,当我有时间时,我可以确认或驳斥这种理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM