/**
(**) 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))
*/
這種匹配對於正常情況下是這樣的:scala模式mathing。什麼是現在
object MatchTest1 extends Application {
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "many"
}
println(matchTest(3))
}
我知道這是tryhing與模式匹配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)
}
由於
該功能的最新主題:https://groups.google.com/d/msg/scala-user/I1kNxYFTG4w/7f5V1IdDDtwJ – 2014-10-08 18:25:11