我是Parser Combinators的新手,在编译以下函数时遇到上述错误:
def attachRoad = "attach" ~ ("primary" | "secondary") ~ "road" ~ ident ~ "with" ~ "length" ~ floatingPointNumber ~ "at" ~ floatingPointNumber ^^
{
case "attach" ~ "primary" ~ "road" ~ road ~ "with" ~ "length" ~ len ~ "at" ~ pos ~ "flow" ~ flow => attachRoadHelper(road, StreetType.PRIMARY, len, flow, pos)
case "attach" ~ "secondary" ~ "road" ~ road ~ "with" ~ "length" ~ len ~ "at" ~ pos ~ "flow" ~ flow => attachRoadHelper(road, StreetType.SECONDARY, len, flow, pos)
}
所以这给了我
constructor cannot be initiated to expected type
在两种情况下都有解释。
再次查看了文档和StackOverflow上的一些线程,我未能找到解决方案或理解为什么会发生这种情况,因为我在“case”语句中没有看到任何构造函数。 (那是Scala在幕后做的事情吗?)
我也尝试将“案例”结果更改为“无”无效。
非常感谢任何见解。
答案 0 :(得分:1)
使用括号对所有重要捕获组进行分组并使用~>
或<~
运算符忽略所有常量标记可能是个好主意。在这种情况下,您只需要匹配重要结果:
def attachRoad =
("attach" ~> ("primary" | "secondary")) ~
("road" ~> ident) ~
("with" ~> "length" ~> floatingPointNumber) ~
("at" ~> floatingPointNumber) ^^ {
case "primary" ~ road ~ len ~ pos =>
attachRoadHelper(road, StreetType.PRIMARY, len, ???, pos)
case "secondary" ~ road ~ len ~ pos =>
attachRoadHelper(road, StreetType.SECONDARY, len, ???, pos)
}
在你的情况下,很明显你的解析表达式返回四个结果的序列,而你期望五个。