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

查看:106
本文介绍了您如何旋转(循环移位)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))
    }
}

但是当我想对整个收藏集进行折叠时,我想知道是否还有一种更惯用的方法。递归方法将使我避免使用任何 var s。但基本上,我想知道是否可能出现以下情况:

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天全站免登陆