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

后端 未结 11 1707
盖世英雄少女心
盖世英雄少女心 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:10

    Following the OP's comment that they want to fold over it, here's a slightly different take on it that avoids calculating the length of the sequence first.

    Define an iterator that will iterate over the rotated sequence

    class RotatedIterator[A](seq: Seq[A], start: Int) extends Iterator[A] {
      var (before, after) = seq.splitAt(start)
      def next = after match {
        case Seq()  =>
          val (h :: t) = before; before = t; h
        case h :: t => after = t; h
      }
      def hasNext = after.nonEmpty || before.nonEmpty
    }
    

    And use it like this:

    val seq = List(1, 2, 3, 4, 5)  
    val xs = new RotatedIterator(seq, 2)
    println(xs.toList)         //> List(3, 4, 5, 1, 2)
    

提交回复
热议问题