Calculating differences of subsequent sequence elements in scala

I would almost certainly do this in scala. Is there an elegant way?

In particular, I just want the difference of adjacent elements in the sequence. for instance

input = 1,2,6,9 output = 1,4,3 
+4
source share
2 answers

How about this?

 scala> List(1, 2, 6, 9).sliding(2).map { case Seq(x, y, _*) => y - x }.toList res0: List[Int] = List(1, 4, 3) 
+8
source

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.

+4
source

Source: https://habr.com/ru/post/1488758/


All Articles