如何实现列表的'takeUntil'?

Fre*_*ind 8 scala list

我希望之前找到所有项目,并且等于第一项7:

val list = List(1,4,5,2,3,5,5,7,8,9,2,7,4)
Run Code Online (Sandbox Code Playgroud)

我的解决方案是:

list.takeWhile(_ != 7) ::: List(7)
Run Code Online (Sandbox Code Playgroud)

结果是:

List(1, 4, 5, 2, 3, 5, 5, 7)
Run Code Online (Sandbox Code Playgroud)

还有其他解决方案吗?

Aiv*_*ean 15

不耐烦的单线:

List(1, 2, 3, 7, 8, 9, 2, 7, 4).span(_ != 7) match {case (h, t) => h ::: t.take(1)}
Run Code Online (Sandbox Code Playgroud)


更通用的版本:

它将任何谓词作为参数.用span做主要工作:

  implicit class TakeUntilListWrapper[T](list: List[T]) {
    def takeUntil(predicate: T => Boolean):List[T] = {
      list.span(predicate) match {
        case (head, tail) => head ::: tail.take(1)
      }
    }
  }

  println(List(1,2,3,4,5,6,7,8,9).takeUntil(_ != 7))
  //List(1, 2, 3, 4, 5, 6, 7)

  println(List(1,2,3,4,5,6,7,8,7,9).takeUntil(_ != 7))
  //List(1, 2, 3, 4, 5, 6, 7)

  println(List(1,2,3,4,5,6,7,7,7,8,9).takeUntil(_ != 7))
  //List(1, 2, 3, 4, 5, 6, 7)

  println(List(1,2,3,4,5,6,8,9).takeUntil(_ != 7))
  //List(1, 2, 3, 4, 5, 6, 8, 9)
Run Code Online (Sandbox Code Playgroud)


尾递归版.

仅仅为了说明替代方法,它并不比以前的解决方案更有效.

implicit class TakeUntilListWrapper[T](list: List[T]) {
  def takeUntil(predicate: T => Boolean): List[T] = {
    def rec(tail:List[T], accum:List[T]):List[T] = tail match {
      case Nil => accum.reverse
      case h :: t => rec(if (predicate(h)) t else Nil, h :: accum)
    }
    rec(list, Nil)
  }
}
Run Code Online (Sandbox Code Playgroud)


mar*_*ios 5

借用takeWhile实现scala.collection.List并稍微改变一下:

def takeUntil[A](l: List[A], p: A => Boolean): List[A] = {
    val b = new scala.collection.mutable.ListBuffer[A]
    var these = l
    while (!these.isEmpty && p(these.head)) {
      b += these.head
      these = these.tail
    }
    if(!these.isEmpty && !p(these.head)) b += these.head

    b.toList
  }
Run Code Online (Sandbox Code Playgroud)