【问题标题】:takeWhile in Scala for element n+1takeWhile 在 Scala 中用于元素 n+1
【发布时间】:2020-05-31 13:31:10
【问题描述】:
  • 定义函数dropWhileSmallerThanFive,它应该取一个列表并丢弃前n个元素,直到下一个元素(n+1)大于或等于5。

    *使用 Scala 的内置列表函数之一(例如 takeWhile)。

我试过这个:

   def dropWhileSmallerThanFive(xs: List[Int]): List[Int] = xs match {
        case Nil => Nil
        case head :: b :: tail if b >= 5 => head :: (b::tail).takeWhile(_>=5)
        case _ => Nil 
    }

但这完全错了,我该怎么办?

【问题讨论】:

    标签: list scala pattern-matching


    【解决方案1】:

    欢迎来到 SO!如果您是 Scala 新手,请考虑以下适合初学者的资源


    Scala 提供了开箱即用的List.dropWhile,或者考虑以下递归实现

    def recDropWhile(l: List[Int], predicate: Int => Boolean): List[Int] = {
      @scala.annotation.tailrec
      def loop(l: List[Int], predicate: Int => Boolean): List[Int] = {
        l match {
          case Nil => Nil
          case head :: tail => if (predicate(head)) loop(tail, predicate) else (head :: tail)
        }
      }
      loop(l, predicate)
    }
    

    两个输出

    val l = List(1,2,3,4,5,6,7,8)
    l.dropWhile(_ < 5)       // res3: List[Int] = List(5, 6, 7, 8)
    recDropWhile(l, _ < 5)   // res4: List[Int] = List(5, 6, 7, 8)
    

    【讨论】:

      猜你喜欢
      • 2016-02-26
      • 1970-01-01
      • 2014-02-06
      • 2013-04-27
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 2014-06-22
      • 2014-06-27
      相关资源
      最近更新 更多