Suppose I have a list of numbers. How to convert the list to a list of their "deltas" -- the pairwise differences of the subsequent numbers?
For example: Given List(5, 2, 1, 1)
I would like to get List(3, 1, 0)
In Scala, you can convert a list to a map in Scala using the toMap method. A map contains a set of values i.e. key-> value but a list contains single values. So, while converting a list to map we have two ways, Add index to list.
This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.
Syntax for defining a Scala List. val variable_name: List[type] = List(item1, item2, item3) or val variable_name = List(item1, item2, item3) A list in Scala is mostly like a Scala array. However, the Scala List is immutable and represents a linked list data structure.
The correct answer is
(xs, xs drop 1).zipped.map(_-_)
And it does not even explode when you pass it an empty or single-digit list.
List(5,2,1,1).sliding(2).map(pair => pair(0) - pair(1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With