How do you rotate (circular shift) of a Scala collection

后端 未结 11 1706
盖世英雄少女心
盖世英雄少女心 2020-12-19 03:40

I can do this quite easily, and cleanly, using a for loop. For instance, if I wanted to traverse a Seq from every element back to itself I would do the

11条回答
  •  爱一瞬间的悲伤
    2020-12-19 04:15

    Here's a fairly simple and idiomatic Scala collections way to write it:

    def rotateSeq[A](seq: Seq[A], isLeft: Boolean = false, count: Int = 1): Seq[A] =
      if (isLeft)
        seq.drop(count) ++ seq.take(count)
      else
        seq.takeRight(count) ++ seq.dropRight(count)
    

提交回复
热议问题