模式匹配期间需要稳定的标识符吗? (斯卡拉)
尝试生成显示质因数重数的元组列表...其想法是将排序列表中的每个整数与元组中的第一个值进行匹配,并使用第二个值进行计数。使用 takeWhile
可能可以更轻松地做到这一点,但是呃。不幸的是,我的解决方案无法编译:
def primeFactorMultiplicity (primeFactors: List[Int]) = {
primeFactors.foldRight (List[(Int, Int)]()) ((a, b) => (a, b) match {
case (_, Nil) => (a, 1) :: b
case (b.head._1, _) => (a, b.head._2 + 1) :: b.tail
case _ => (a, 1) :: b
})
}
它显示“错误:需要稳定标识符,但找到了 b.head._1”。但是将第二个 case
行更改为以下内容可以正常工作:
case (i, _) if (i == b.head._1) => (a, b.head._2 + 1) :: b.tail
为什么会这样,如果有如此简单的修复,为什么编译器无法应对?
Trying to produce a list of tuples showing prime factor multiplicity... the idea is to match each integer in a sorted list against the first value in a tuple, using the second value to count. Could probably do it more easily with takeWhile
, but meh. Unfortunately my solution won't compile:
def primeFactorMultiplicity (primeFactors: List[Int]) = {
primeFactors.foldRight (List[(Int, Int)]()) ((a, b) => (a, b) match {
case (_, Nil) => (a, 1) :: b
case (b.head._1, _) => (a, b.head._2 + 1) :: b.tail
case _ => (a, 1) :: b
})
}
It says "error: stable identifier required, but b.head._1 found." But changing the second case
line to the following works fine:
case (i, _) if (i == b.head._1) => (a, b.head._2 + 1) :: b.tail
Why is this, and why can't the compiler cope if there is such a simple fix?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
模式中的变量捕获该位置的值;它不进行比较。如果语法完全有效,结果将是将
a
的值放入b.head._1
中,覆盖当前值。这样做的目的是让您使用模式从复杂的结构中提取某些内容。A variable in a pattern captures the value in that position; it does not do a comparison. If the syntax worked at all, the result would be to put the value of
a
intob.head._1
, overwriting the current value. The purpose of this is to let you use a pattern to pull something out of a complex structure.b.head._1
不是(x, y)
元组提取器结果的有效名称请尝试以下操作:
b.head._1
is not a valid name for the result of the(x, y)
tuple extractorTry this instead: