6

我想在scala中几乎完全做到这一点。有没有优雅的方法?

具体来说,我只想要序列中相邻元素的差异。例如

input = 1,2,6,9
output = 1,4,3
4

2 回答 2

12

这个怎么样?

scala> List(1, 2, 6, 9).sliding(2).map { case Seq(x, y, _*) => y - x }.toList
res0: List[Int] = List(1, 4, 3)
于 2013-06-28T19:56:21.307 回答
5

这是一个使用递归并且在列表上效果最好的方法

def differences(l:List[Int]) : List[Int] = l match {
  case a :: (rest @ b :: _) => (b - a) :: differences(rest)
  case _ => Nil
}

这是一个在 Vector 或 Array 上应该非常快的:

def differences(a:IndexedSeq[Int]) : IndexedSeq[Int] = 
  a.indices.tail.map(i => a(i) - a(i-1))

当然,总是这样:

def differences(a:Seq[Int]) : Seq[Int] = 
  a.tail.zip(a).map { case (x,y) => x - y }

请注意,只有递归版本无一例外地处理空列表。

于 2013-06-28T20:24:39.277 回答