你如何旋转(循环移位)Scala 集合 [英] How do you rotate (circular shift) of a Scala collection

查看:17
本文介绍了你如何旋转(循环移位)Scala 集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用 for 循环很容易、干净地做到这一点.例如,如果我想从每个元素遍历 Seq 回到自身,我会执行以下操作:

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 following:

val seq = Seq(1,2,3,4,5)

for (i <- seq.indices) {
    for (j <- seq.indices) {
        print(seq(i + j % seq.length))
    }
}

但是当我希望在集合上 fold 时,我想知道是否有更惯用的方法.递归方法可以让我避免任何 vars.但基本上,我想知道是否可能出现以下情况:

But as I'm looking to fold over the collection, I'm wondering if there is a more idiomatic approach. A recursive approach would allow me to avoid any vars. But basically, I'm wondering if something like the following is possible:

seq.rotatedView(i)

这将创建一个旋转的视图,例如旋转位(或循环移位).

Which would create a rotated view, like rotating bits (or circular shift).

推荐答案

根据 OP 的评论,他们想要折叠它,这里有一个稍微不同的看法,避免先计算序列的长度.

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
}

并像这样使用它:

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

这篇关于你如何旋转(循环移位)Scala 集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆