Scala - increasing prefix of a sequence

后端 未结 4 680
离开以前
离开以前 2021-01-18 21:02

I was wondering what is the most elegant way of getting the increasing prefix of a given sequence. My idea is as follows, but it is not purely functional or any elegant:

4条回答
  •  爱一瞬间的悲伤
    2021-01-18 21:37

    If by elegant you mean concise and self-explanatory, it's probably something like the following:

    sequence.inits.dropWhile(xs => xs != xs.sorted).next
    

    inits gives us an iterator that returns the prefixes longest-first. We drop all the ones that aren't sorted and take the next one.

    If you don't want to do all that sorting, you can write something like this:

    sequence.scanLeft(Some(Int.MinValue): Option[Int]) {
      case (Some(last), i) if i > last => Some(i)
      case _ => None
    }.tail.flatten
    

    If the performance of this operation is really important, though (it probably isn't), you'll want to use something more imperative, since this solution still traverses the entire collection (twice).

提交回复
热议问题