/**
(**) Pack consecutive duplicates of list elements into sublists.
If a list contains repeated elements they should be placed in separate sublists.
Example:
scala> pack(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
res0: List[List[Symbol]] = List(List('a, 'a, 'a, 'a), List('b), List('c, 'c), List('a, 'a), List('d), List('e, 'e, 'e, 'e))
*/
正常情况如下:
object MatchTest1 extends Application {
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "many"
}
println(matchTest(3))
}
我知道尝试将x
与模式匹配。
但是如下所示,它匹配什么?
// 1- My solution
/**
* Similar solution to recusive P08 solution
*/
def pack(input: List[Any]): List[List[Any]] = {
def comp(l: List[Any], lastElem: Any, lastList: List[Any]): List[List[Any]] = {
l match {
case Nil => List[List[Any]](lastList)
case head :: tail if head == lastElem => comp(tail, head, head :: lastList)
case head :: tail if lastList == Nil => comp(tail, head, head :: Nil)
case head :: tail => lastList :: comp(tail, head, head :: Nil)
}
}
comp(input, Nil, Nil)
}
由于
答案 0 :(得分:0)
检查List[Any] l
以下内容:
// Is it an empty list?
case Nil => ...
// Is it not empty and does the first item (the head) equal `lastElem`?
case head :: tail if head == lastElem => ...
// Is it not emptybut lastList is empty?
case head :: tail if lastList == Nil => ...
// Every other case
case head :: tail => ...
如果列表中包含 head (第一项)和 tail (列表的其余部分),则head :: tail
匹配。 head 必须是商品, tail 可以是空列表。这意味着[1]
和[1, 2]
都匹配head :: tail
,而[]仅匹配Nil
。