Scala模式匹配错误,";错误的简单模式:错误使用“*(不允许使用序列模式)”;
我在写Coursera的作业时遇到了一个关于Scala模式匹配的问题 《Scala编程》一书的代码如下:Scala模式匹配错误,";错误的简单模式:错误使用“*(不允许使用序列模式)”;,scala,pattern-matching,Scala,Pattern Matching,我在写Coursera的作业时遇到了一个关于Scala模式匹配的问题 《Scala编程》一书的代码如下: expr match { case List(0, _ * ) => println("found it") case _ => } 因此,我编写了一个类似的代码来计算列表中每个字符的频率: /** * This function computes for each unique character in the list `chars` the num
expr match {
case List(0, _ * ) => println("found it")
case _ =>
}
因此,我编写了一个类似的代码来计算列表中每个字符的频率:
/**
* This function computes for each unique character in the list `chars` the number of
* times it occurs. For example, the invocation
*
* times(List('a', 'b', 'a'))
*
* should return the following (the order of the resulting list is not important):
*
* List(('a', 2), ('b', 1)) */
def times(chars: List[Char]): List[(Char, Int)] = {
def addTime(char: Char, times: List[(Char, Int)]):List[(Char, Int)] = times match {
case List(head @ (_*), (c , times), tail @ (_*)) if c == char => List(head, (c, times + 1), tail)
case _ => List((char, 1))
}
if(chars.isEmpty) Nil else addTime(chars.head, times(chars.tail))
}
但是,编译器抱怨:
Error:(81, 29) bad simple pattern: bad use of _* (sequence pattern not allowed)
case List(head @ (_*), (c , times), tail @ (_*)) if c == char => List(head, (c, times + 1), tail)
虽然我用另一种方法成功地实现了这个方法,但在2个helper函数的帮助下,我不知道为什么不允许使用这个序列模式。我试图用谷歌搜索,但找不到答案
如有任何建议,将不胜感激。提前感谢。任何模式匹配最多只能以一种方式分解原始值。如果
案例列表(head@(*)、(c,times)、tail@(*)
是合法的,它将允许head
、c
、times
和tail
的许多选项。您的意图似乎是按顺序尝试所有这些方法,并在guardc==char
变为true时进行匹配,但这不是Scala模式匹配的工作方式
事实上,为了简化规则,只允许在末尾使用
.*
。类似于List(*,c)
的东西可以被合理地允许,但事实并非如此 我有点难以理解,你的代码应该表达什么,我想我最终发现了(带两倍“@”符号的行):匹配一个列表,其中元组(c,n)有一个c,匹配(char)。我对@语法及其用例并不十分熟悉,但从未见过像这样的头和尾的多个可变长度匹配。另外要注意的是,数据结构并不能保证c语言中只有一个匹配。因为我怀疑你对*-thingy更感兴趣,所以我不会发布我自己的解决方案(foldLeft+模式匹配)@userunknown谢谢你,伙计。你说的正是我想要匹配的。原因是,正如你建议的那样,*不允许在头部使用。非常感谢!我的错误是按照你的建议把*放在头上。我再次阅读了pattern match一章,其中有一句话:“如果你想匹配一个序列而不指定它可以有多长,你可以指定*作为模式的最后一个元素。”