Reputation: 37
I was trying to solve breaktherope challenge of codility in scala but i could not come up with a functional solution. The snippet below is an example of where i'm stuck. Both list elements have to change throughtout the program . Can we solve this with map or sth like that?
var A = MutableList(5, 3, 6, 3, 3)
var B = MutableList(2, 3, 1, 1, 2)
for (i <- 0 to N){
A(i) -= B(i)
}
Upvotes: 0
Views: 59
Reputation: 367
One little enhancement to Maxim's answer would be the use of scala's for comprehensions, just to get a more declarative solution:
val result = for {
(a, b) <- A zip B
} yield a - b
Upvotes: 0
Reputation: 7348
A functional solution will return a new list and not a mutation of A.
val result = A.zip(B).map { case (a, b) => a - b}
if A, B are immutable the list will be immutable as well. If A, B are mutable you can convert the result to immutable list using .toList
Upvotes: 3