【问题标题】:How to implement 'takeUntil' of a list?如何实现列表的“takeUntil”?
【发布时间】:2016-02-09 17:17:29
【问题描述】:

我想找到之前的所有项目并且等于第一个7

val list = List(1,4,5,2,3,5,5,7,8,9,2,7,4)

我的解决办法是:

list.takeWhile(_ != 7) ::: List(7)

结果是:

List(1, 4, 5, 2, 3, 5, 5, 7)

还有其他解决办法吗?

【问题讨论】:

  • 7 不应包括在内,根据标准库的定义:scala> List(1,4,5,2,3,5,5,7,8,9,2,7,4).takeWhile(_ != 7) res0: List[Int] = List(1, 4, 5, 2, 3, 5, 5)。提示 - 考虑使用List#foldRight

标签: list scala


【解决方案1】:

不耐烦的单线:

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


更通用的版本:

它接受任何谓词作为参数。使用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)


尾递归版本。

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

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)
  }
}

【讨论】:

    【解决方案2】:

    scala.collection.List 借用 takeWhile 实现并稍作改动:

    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
      }
    

    【讨论】:

    • 但总的来说,我觉得你的问题几乎是最短且不那么冗长的方法。
    • 我使用这个答案是因为我实际上想要spanUntil - 这可以节省列表的迭代。
    【解决方案3】:

    这是一种使用 foldLeft 实现目标的方法,以及用于缩短长列表的尾递归版本。

    还有我在玩这个时使用的测试。

    import scala.annotation.tailrec
    import org.scalatest.WordSpec
    import org.scalatest.Matchers
    
    object TakeUntilInclusiveSpec {
      implicit class TakeUntilInclusiveFoldLeft[T](val list: List[T]) extends AnyVal {
        def takeUntilInclusive(p: T => Boolean): List[T] =
          list.foldLeft( (false, List[T]()) )({
            case ((false, acc), x)      => (p(x), x :: acc)
            case (res @ (true, acc), _) => res
          })._2.reverse
      }
      implicit class TakeUntilInclusiveTailRec[T](val list: List[T]) extends AnyVal {
        def takeUntilInclusive(p: T => Boolean): List[T] = {
          @tailrec
          def loop(acc: List[T], subList: List[T]): List[T] = subList match {
            case Nil => acc.reverse
            case x :: xs if p(x) => (x :: acc).reverse
            case x :: xs => loop(x :: acc, xs)
          }
          loop(List[T](), list)
        }
      }
    }
    
    class TakeUntilInclusiveSpec extends WordSpec with Matchers {
      //import TakeUntilInclusiveSpec.TakeUntilInclusiveFoldLeft
      import TakeUntilInclusiveSpec.TakeUntilInclusiveTailRec
    
      val `return` = afterWord("return")
      object lists {
        val one = List(1)
        val oneToTen = List(1, 2, 3, 4, 5, 7, 8, 9, 10)
        val boat = List("boat")
        val rowYourBoat = List("row", "your", "boat")
      }
    
      "TakeUntilInclusive" when afterWord("given") {
        "an empty list" should `return` {
          "an empty list" in {
            List[Int]().takeUntilInclusive(_ == 7) shouldBe Nil
            List[String]().takeUntilInclusive(_ == "") shouldBe Nil
          }
        }
    
        "a list without the matching element" should `return` {
          "an identical list" in {
            lists.one.takeUntilInclusive(_ == 20) shouldBe lists.one
            lists.oneToTen.takeUntilInclusive(_ == 20) shouldBe lists.oneToTen
            lists.boat.takeUntilInclusive(_.startsWith("a")) shouldBe lists.boat
            lists.rowYourBoat.takeUntilInclusive(_.startsWith("a")) shouldBe lists.rowYourBoat
          }
        }
    
        "a list containing one instance of the matching element in the last index" should `return`
        {
          "an identical list" in {
            lists.one.takeUntilInclusive(_ == 1) shouldBe lists.one
            lists.oneToTen.takeUntilInclusive(_ == 10) shouldBe lists.oneToTen
            lists.boat.takeUntilInclusive(_ == "boat") shouldBe lists.boat
            lists.rowYourBoat.takeUntilInclusive(_ == "boat") shouldBe lists.rowYourBoat
          }
        }
    
        "a list containing one instance of the matching element" should `return` {
          "the elements of the original list, up to and including the match" in {
            lists.one.takeUntilInclusive(_ == 1) shouldBe List(1)
            lists.oneToTen.takeUntilInclusive(_ == 5) shouldBe List(1,2,3,4,5)
            lists.boat.takeUntilInclusive(_ == "boat") shouldBe List("boat")
            lists.rowYourBoat.takeUntilInclusive(_ == "your") shouldBe List("row", "your")
          }
        }
    
        "a list containing multiple instances of the matching element" should `return` {
          "the elements of the original list, up to and including only the first match" in {
            lists.oneToTen.takeUntilInclusive(_ % 3 == 0) shouldBe List(1,2,3)
            lists.rowYourBoat.takeUntilInclusive(_.length == 4) shouldBe List("row", "your")
          }
        }
      }
    }
    

    【讨论】:

    • 顺序变了:(
    • 没关系,我的 takeWhile 和 dropWhile 已切换。
    • 如果列表不包含7,这将添加一个 - 这可能是也可能不是 OP 想要的,但对我来说似乎有点可疑(特别是因为它 不会对空列表这样做)。
    • 仅供参考,使用:+ 将元素附加到List 效率极低。目前您的解决方案是 O(N^2)。将累加器替换为ListBuffer,或者使用::(前置)和reverse作为最后的结果。
    • @Aivean 这应该只是一个快速演示版本,但它一直困扰着我。所以这是一个 O(n) foldLeft 解决方案,如果我必须在生产代码中执行类似的操作,我会实际使用 O(n) 尾递归版本。
    【解决方案4】:

    这样做的可能方式:

    def takeUntil[A](list:List[A])(predicate: A => Boolean):List[A] =
      if(list.isEmpty) Nil
      else if(predicate(list.head)) list.head::takeUntil(list.tail)(predicate)
      else List(list.head)
    

    【讨论】:

    • 仅供参考,这种方法不是尾递归的(在长输入列表上可能会失败)。
    【解决方案5】:

    您可以使用以下功能,

    def takeUntil(list: List[Int]): List[Int] = list match {
      case x :: xs if (x != 7) => x :: takeUntil(xs)
      case x :: xs if (x == 7) => List(x)
      case Nil => Nil
    }
    
    val list = List(1,4,5,2,3,5,5,7,8,9,2,7,4)
    takeUntil(list) //List(1,4,5,2,3,5,5,7)
    

    尾递归版本

    def takeUntilRec(list: List[Int]): List[Int] = {
        @annotation.tailrec
        def trf(head: Int, tail: List[Int], res: List[Int]): List[Int] = head match {
          case x if (x != 7 && tail != Nil) => trf(tail.head, tail.tail, x :: res)
          case x                            => x :: res
        }
        trf(list.head, list.tail, Nil).reverse
      }
    

    【讨论】:

    • 这个函数不是尾递归的,所以它可能会因 StackOverflow 的长列表而失败。仅供参考。
    【解决方案6】:

    使用内置函数的一些方法:

    
    val list = List(1, 4, 5, 2, 3, 5, 5, 7, 8, 9, 2, 7, 4)
    //> list  : List[Int] = List(1, 4, 5, 2, 3, 5, 5, 7, 8, 9, 2, 7, 4)
    //Using takeWhile with dropWhile
    list.takeWhile(_ != 7) ++ list.dropWhile(_ != 7).take(1)
    //> res0: List[Int] = List(1, 4, 5, 2, 3, 5, 5, 7)
    //Using take with segmentLength
    list.take(list.segmentLength(_ != 7, 0) + 1)
    //> res1: List[Int] = List(1, 4, 5, 2, 3, 5, 5, 7) //Using take with indexOf list.take(list.indexOf(7) + 1) //> res2: List[Int] = List(1, 4, 5, 2, 3, 5, 5, 7)

    【讨论】:

      【解决方案7】:

      这里的许多解决方案效率不高,因为它们会探索整个列表,而不是提前停止。这是使用内置函数的简短解决方案:

      def takeUntil[T](c: Iterable[T], f: T => Boolean): Iterable[T] = {
         val index = c.indexWhere(f)
         if (index == -1) c else c.take(index + 1)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-16
        • 2021-10-13
        相关资源
        最近更新 更多