Scala - increasing prefix of a sequence

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

    And, another way to skin the cat:

     val sequence = Seq(1,2,3,1,2,3,4,5,6)
     sequence.head :: sequence
                      .sliding(2)
                      .takeWhile{case List(a,b) => a <= b}
                      .map(_(1)).toList
    // List[Int] = List(1, 2, 3)
    

提交回复
热议问题