I was writing an assignment from Coursera and I met a problem about Scala Pattern Matching.
The book "Programming in Scala" has the following code:
expr match {
case List(0, _ * ) => println("found it")
case _ =>
}
So I wrote a similiar code to calculate the frequency of each character in a list:
/**
* 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))
}
However, the compiler complains:
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)
Though I successfully implemented this method in another way, with the help of 2 helper functions, I did not know why does this sequence pattern was not allowed. I tried to Google but I could not find an answer.
Any suggestion will be appreciated. Thanks in advance.