2014-10-08 100 views
0
/** 
(**) 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) 
    } 

由於

+0

該功能的最新主題:https://groups.google.com/d/msg/scala-user/I1kNxYFTG4w/7f5V1IdDDtwJ – 2014-10-08 18:25:11

回答

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匹配如果該列表具有(第一項)和(該列表的其餘部分)。 頭部必須是一個項目,尾部可以是一個空的列表。這意味着[1][1, 2]將匹配head :: tail,而[]只會匹配Nil

+0

另外,「head」和「tail」僅僅是標識符。 'x :: y'也可以。 ('[1]'不是列表,也不是'[1,2]',btw) – 2014-10-08 19:49:22

+0

@Paul True。混亂的語言。製作該列表(1,2)和列表(1)。 – 2014-10-08 20:44:26