Wednesday, October 7, 2009

P07: Flatten a list

Just use flatten method:
scala> val m = List(List(1, 2), List(3, 4))
res2: List[List[Int]] = List(List(1, 2), List(3, 4))

scala> m.flatten
res3: List[Int] = List(1, 2, 3, 4)

Just out of sheer curiosity, here another implementation with much better performace:

scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer

scala> def myFlatten[T](nl:List[List[T]]):List[T] = {
| val b = new ListBuffer[T]
| for(list<-nl){
| var tlist = list
| while(!tlist.isEmpty){
| b+=tlist.head
| tlist = tlist.tail
| }
| }
| b.toList
| }
myFlatten: [T](nl: List[List[T]])List[T]

scala> myFlatten(m)
res1: List[Int] = List(1, 2, 3, 4)

No comments:

Post a Comment