Scala:采取流程"同时增加"

时间:2016-09-07 07:23:40

标签: scala collections

我想遍历一个序列:

val data = Seq(1,2,3,4,5,5,6,7,8)

我的目标是构建一个新序列,但只将数据提升到其值停止增加的点。因此,在这种情况下,所需的输出为Seq(1,2,3,4,5)

我认为解决方案在于使用takeWhilesliding(以访问下一个值),但我无法弄清楚如何将它们组合起来。

4 个答案:

答案 0 :(得分:1)

我找到了解决方案:

val strictIncreasingData = 
(Seq(Int.MinValue)++data).sliding(2).takeWhile{case Seq(current,next) => next>current}.map{case Seq(current,next) => next}.toSeq

诀窍是将Iterator(从sliding)转换回序列。 Int.MinValue的前置确保不会吞下任何元素。此解决方案不适用于空集合

答案 1 :(得分:1)

整蛊,但正在努力:

data
  .view
  .scanLeft(Option.empty[Int]) {
    case (None, item) => Option(item)
    case (Some(prev), item) => Option(item).filter(cur => cur > prev)
  }
  .tail
  .takeWhile(_.isDefined)
  .flatten

答案 2 :(得分:0)

拉链尾巴

data zip data.tail takeWhile { case (a, b) => a < b } map (_._1) toSeq

答案 3 :(得分:0)

集合API之外有答案;)

这可以重构为更具可读性的东西。只是给人一种印象:

def takeWhileIncreasing(in: Seq[Int]): Seq[Int] = {
  @tailrec def internal(in: Seq[Int], out: Seq[Int]): Seq[Int] = {
    in match {
      case prev +: (tail @ (next +: _)) if next > prev =>
        internal(tail, prev +: out)
      case prev +: (tail @ (next +: _)) if next <= prev =>
        prev +: out
      case _ =>
        out
    }
  }

  internal(in, Seq.empty).reverse
}
相关问题