Reputation:
I am trying to write a function in Scala which takes two integer lists xs
and ys
and does the following:
subtracts element by element ys
from xs
. An example: List(1,2,4)
and List(3,2,1)
gets you List(-2, 0, 3)
filters out all elements less than or equal to 0 from the list resulting from step 1.
I am trying to do this using the list functions from the Scala Standard Library
object Solution {
def combineSubAndFilter(xs: List[Int], ys: List[Int]) = ???
}
Upvotes: 0
Views: 132
Reputation: 8529
The answer, as suggested in the comments by @Luis is:
def combineSubAndFilter(xs: List[Int], ys: List[Int]) = xs.zipAll(ys, 0, 0).collect { case (x,y) if (x > y) => x-y }
From zipAll
documentation:
Returns a $coll formed from this $coll and another iterable collection by combining corresponding elements in pairs. If one of the two collections is shorter than the other, placeholder elements are used to extend the shorter collection to the length of the longer.
Code run can be found at Scastie.
Upvotes: 4