Scala - increasing prefix of a sequence

后端 未结 4 708
离开以前
离开以前 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:30

    You can take your solution, @Samlik, and effectively zip in the currentElement variable, but then map it out when you're done with it.

    sequence.take(1) ++ sequence.zip(sequence.drop(1)).
        takeWhile({case (a, b) => a < b}).map({case (a, b) => b})
    

    Also works with infinite sequences:

    val sequence = Seq(1, 2, 3).toStream ++ Stream.from(1)
    

    sequence is now an infinite Stream, but we can peek at the first 10 items:

    scala> sequence.take(10).toList
    res: List[Int] = List(1, 2, 3, 1, 2, 3, 4, 5, 6, 7)
    

    Now, using the above snippet:

    val prefix = sequence.take(1) ++ sequence.zip(sequence.drop(1)).
        takeWhile({case (a, b) => a < b}).map({case (a, b) => b})
    

    Again, prefix is a Stream, but not infinite.

    scala> prefix.toList
    res: List[Int] = List(1, 2, 3)
    

    N.b.: This does not handle the cases when sequence is empty, or when the prefix is also infinite.

提交回复
热议问题