问题描述
我想在 Scala 中用数字减去列表中的两个连续元素.
I would like to subtract two consecutive element in a list with numbers in Scala.
例如:我有此列表:
val sortedList = List(4,5,6)
我想要一个输出列表,例如 diffList =(1,1)
,其中 5-4 = 1
和 6-5 = 1 代码>.
I would like to have an output list like diffList =(1, 1)
where 5-4 = 1
and 6-5 = 1
.
我尝试了以下代码:
var sortedList = List[Int]()
var diffList = List[Int]()
for (i <- 0 to (sortedList.length - 1) ;j <- i + 1 to sortedList.length - 1)
{
val diff = (sortedList(j) - sortedList(i))
diffList = diffList :+ diff
}
对于 diffList =(1、2、1)
,我有以下结果,但是我想要 diffList =(1,1)
.
I have the following result for diffList =(1, 2, 1)
but I want diffList = (1,1)
.
这是因为for循环.它不会一次遍历两个变量(i和j).
It's because of the for loop. it does not iterate over the two variables (i and j) at once.
推荐答案
解决问题的方法不是可变性,也不是命令式编程,功能性编程使您覆盖了.
You do not mutability nor imperative programming to solve this problem, functional programming got you covered.
def consecutiveDifferences(data: List[Int]): List[Int] =
if (data.isEmpty) List.empty
else data.lazyZip(data.tail).map {
case (x, y) => y - x
}
就像我经常说的那样,> Scaladoc 是你的朋友.
(另外,作为建议,学习函数式编程的最佳方法是禁止自己的可变性)
As I always say, the Scaladoc is your friend.
(Also, as an advice, the best way to learn functional programming is to forbid yourself from mutability)
这篇关于如何在Scala的列表中减去两个连续的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!