简体   繁体   English

了解解析器组合器〜输出

[英]Understanding Parser Combinator ~ Output

Reading DSLs in Action , I saw this code for the Sequential Combinator : 通过阅读DSL ,我看到了Sequential Combinator以下代码:

def ~ [U](p: => Parser[U]): Parser[~[T, U]] =
(for(a <- this; b <- p) yield new ~(a,b)).named("~")

What is the meaning of the return type: Parser[~[T, U]] ? 返回类型: Parser[~[T, U]]的含义是什么?

Is the return type a Parser containing a type that's the result of applying ~ to arguments of type T and U ? 返回类型是否为Parser包含的类型是将~应用于类型TU参数的结果?

The type ~ is basically a tuple type that allows an infix notation. 类型~基本上是一个允许使用前缀表示法的元组类型。 So the returned parser in the question parses a type that is isomorphic to (T,U) . 因此,问题中返回的解析器将解析与(T,U)同构的类型。 The infix notation allows to write the following: 中缀符号允许编写以下内容:

def intParser: Parser[Int] = ???
def intPair: Parser[~[Int,Int]] = intParser ~ intParser
def product: Parser[Int] = intPair ^^ {case f1 ~ f2 => f1 * f2}

Or in one line, as it's usually done: 或一行完成,通常这样做:

def product: Parser[Int] = intParser ~ intParser ^^ {case f1 ~ f2 => f1 * f2}

Or maybe a bit more sane, with the numbers separated by a * : 或者更合理一些,用*隔开数字:

def product: Parser[Int] = intParser ~ ("*" ~> intParser) ^^ {case f1 ~ f2 => f1 * f2}

Note that ~> drops the left hand side. 注意~>放到左侧。

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

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