根据谓词拆分器将对象列表拆分为不同的列表

时间:2015-01-05 00:35:30

标签: scala scala-collections

我有一个这样的清单:

val data = List("a","b","","c","d","e","","a","b","c")

我想将它从元素"":

中分离出来
List(List("a","b"),List("c","d","e"),List("a","b","c"))

Scala的方式是什么?

类似的东西:

data.MAGIC(_=="")

3 个答案:

答案 0 :(得分:3)

使用span

def magic[T](l: List[T]): List[List[T]] = {
  @tailrec
  def magicAux[T](l: List[T], r: MutableList[List[T]]): MutableList[List[T]] = {
    val (p, s) = l.span(_ != "")
    s match {
      case Nil => r += p
      case _   => magicAux(s.tail, r += p)
    }
  }
  magicAux(l, new MutableList[List[T]]()).toList
}  

答案 1 :(得分:1)

这个怎么样:

scala> Stream.iterate(""::data){ _.tail.dropWhile(_.nonEmpty) }
       .takeWhile(_.nonEmpty)
       .map{ _.tail.takeWhile(_.nonEmpty) }.toList
res1: List[List[String]] = List(List(a, b), List(c, d, e), List(a, b, c))

或者这个:

scala> (-1 +: data.zipWithIndex.collect{ case ("", i) => i } :+ data.size)
       .sliding(2).toList
       .map{ case List(h, t) => data.slice(h+1,t) }
res2: List[List[String]] = List(List(a, b), List(c, d, e), List(a, b, c))

这一个:

scala> (data:+"").foldLeft(List[List[String]](), List[String]()){ 
         case((xs, x), v) => if(v.isEmpty) (x.reverse::xs, Nil) else (xs,v::x) 
       }._1.reverse
res3: List[List[String]] = List(List(a, b), List(c, d, e), List(a, b, c))

答案 2 :(得分:0)

使用foldRight

  val res = ("" :: data).foldRight(List[List[_]](Nil))((x, s) =>
    (x, s) match {
      case ("", Nil :: _) => s
      case ("", _)        => Nil :: s
      case (x, h :: t)    => (x :: h) :: t
    }).tail