Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a list of numbers to the list of their deltas in Scala?

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)

like image 490
Michael Avatar asked Nov 11 '11 18:11

Michael


People also ask

How do I convert a list to map in Scala?

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.

How do I append to a list in Scala?

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”.

How do I create a list in Scala?

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.


2 Answers

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.

like image 189
Luigi Plinge Avatar answered Sep 30 '22 21:09

Luigi Plinge


List(5,2,1,1).sliding(2).map(pair => pair(0) - pair(1))
like image 40
Tomasz Nurkiewicz Avatar answered Sep 30 '22 20:09

Tomasz Nurkiewicz