Raphael Roth Raphael Roth - 2 months ago 8
Scala Question

Scala: take stream "while increasing"

I want to traverse a sequence:

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


My goal is to build a new sequence but only take data up to the point where the their values stop increasing. So the desired output would be
Seq(1,2,3,4,5)
in this case.

I think the solution lies in using
takeWhile
and
sliding
(to access the next value), but I cannot figure out how to combine them.

Answer

Tricky, but working:

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