成对转换 Scala 序列

Transform a Scala Sequence in Pairs

我有一个这样的序列:

val l = Seq(1,2,3,4)

我想转换成 List(Seq(1,2), Seq(2,3), Seq(3,4))

这是我尝试过的:

def getPairs(inter: Seq[(Int, Int)]): Seq[(Int, Int)] = l match {
 case Nil => inter
 case x :: xs => getPairs(inter :+ (x, xs.head))
}

奇怪的是,这似乎不起作用?有什么建议吗?

好的,我了解了 zip 方法:

xs zip xs.tail

您也可以只使用sliding:

l.sliding(2).toList
res1: List[Seq[Int]] = List(List(1, 2), List(2, 3), List(3, 4))

已经给出的答案很好地描述了如何以 Scala 方式执行此操作。 但是,您可能还需要解释为什么您的代码不起作用,所以它来了:

您的 getPairs 函数需要一个元组列表作为输入,returns 一个元组列表。但是您说您想将单个值列表转换为元组列表。因此,如果您调用 getPairs(l),您将收到 type mismatch 编译器错误。

您将不得不重构您的代码以获取一个简单的列表:

def pairs(in: Seq[Int]): Seq[(Int, Int)] = {
  @tailrec
  def recursive(remaining: Seq[Int], result: Seq[(Int, Int)]): Seq[(Int, Int)] = {
    remaining match {
      case Nil => result
      case last +: Nil => result
      case head +: next +: tail => recursive(next +: tail, (head, next) +: result)
    }
  }

  recursive(in, Nil).reverse
}

从这里开始,这是向通用函数迈出的一小步:

def pairs2[A](in: Seq[A]): Seq[(A, A)] = {
  @tailrec
  def recursive(remaining: Seq[A], result: Seq[(A, A)]): Seq[(A, A)] = {
    remaining match {
      case Nil => result
      case last +: Nil => result
      case head +: next +: tail => recursive(next +: tail, (head, next) +: result)
    }
  }

  recursive(in, Nil).reverse
}

使用a进行理解,例如如下,

for ( (a,b) <- l zip l.drop(1) ) yield Seq(a,b)

注意 l.drop(1)(与 l.tail 相反)如果 l 为空或最多只有一项,则将提供一个空列表。