Here is one that uses recursion and works best on lists
def differences(l:List[Int]) : List[Int] = l match { case a :: (rest @ b :: _) => (b - a) :: differences(rest) case _ => Nil }
And here is one that should be pretty fast on Vector or Array:
def differences(a:IndexedSeq[Int]) : IndexedSeq[Int] = a.indices.tail.map(i => a(i) - a(i-1))
Of course, there is always the following:
def differences(a:Seq[Int]) : Seq[Int] = a.tail.zip(a).map { case (x,y) => x - y }
Please note that only the recursive version processes empty lists without exception.
source share