Reputation: 24938
I've these 2 lists:
val forecast = listOf(30, 21, 29, 31, 40, 48, 53, 47, 37, 39, 31, 29)
val actual = listOf(27, 31, 27, 26, 21, 13, 21, 18, 33, 35, 40, 36)
And need to calculate the forecast error in each month, which is forecast-actual
, so I tried the below:
var errors: MutableList<Double> = mutableListOf<Double>()
actual
.forEachIndexed { index, d -> forecast[index] - d}
.let { i -> errors.add(i) }
But did not work, as the i
resulted from forEachIndexed
is a Unit
not a Double
:(
Upvotes: 3
Views: 12778
Reputation: 5963
You want to do more of a map than a forEach. I would do the following then get it into whatever type you're looking for (if you actually want a mutable list of double):
val errors = forecast.zip(actual).map { it.first - it.second }
Zipping the lists together gives you a list of tuples where the first value comes from the first list (forecast), and the second value comes from the second list (actual). Then you can map that list to the difference between the values in each tuple. Map returns a new list with the changes applied to each item, whereas forEach performs the function on each item but doesn't generate a new list.
Or a more lean way:
val errors = forecast.zip(actual){f,a -> f-a)
Upvotes: 13
Reputation: 29844
Problem:
You apply let
on the returned value of forEachIndex
, which is Unit
.
Solution:
actual.forEachIndexed { index, d ->
errors.add(forecast[index] - d.toDouble())
}
Upvotes: 0
Reputation: 691665
Just use mapIndexed instead of foreachIndexed:
val result = forecast.mapIndexed { i, f -> f - actual[i] }
(or, of course):
val result = actual.mapIndexed { i, a -> forecast[i] - a }
Upvotes: 3