2012-07-27 127 views

回答

1

這是幫助我瞭解如何扁平化的工作。

val a = List(List(Map(11 -> 11), Map(12 -> 12)), List(Map(21 -> 21), Map(21 -> 21))) 

def flatten(ls: List[Any]): List[Any] = ls flatMap { 
    case ms: List[_] => flatten(ms) 
    case e => List(e) 
} 

flatten(a) 

/** Converts this $coll of traversable collections into 
    * a $coll in which all element collections are concatenated. 
    * 
    * @tparam B the type of the elements of each traversable collection. 
    * @param asTraversable an implicit conversion which asserts that the element 
    *   type of this $coll is a `Traversable`. 
    * @return a new $coll resulting from concatenating all element ${coll}s. 
    * @usecase def flatten[B]: $Coll[B] 
    */ 
def flatten[B](implicit asTraversable: A => /*<:<!!!*/ TraversableOnce[B]): CC[B] = { 
    val b = genericBuilder[B] // incrementally build 
    for (xs <- sequential) // iterator for your collection 
     b ++= asTraversable(xs) // am i traversable ? 
    b.result     // done ... build me 
} 
+0

這不是如何「真正的」'但是.flatten'工作,:1)這將消除所有嵌套'列表'而不僅僅是一個圖層。 b)你應該比返回任何''更好。 c)正確的'.flatten':'ls flatMap {case x => x}' – Debilski 2012-07-30 07:21:20

+0

我從來沒有聲稱這是多麼平坦的工作。 – 2012-08-01 06:02:46

8

給出無約束:

list.flatten 
相關問題