Consider the following:
val stuff = Map[String, Int]("apple" -> 5, "orange" -> 1, "banana" -> 3, "kiwi" -> 2)
val used = 1
val rest = stuff.mapValues{
case quantity => quantity - used
}.filterNot{
case (fruit, quantity) => quantity == 0
}
The result is
rest : scala.collection.immutable.Map[String,Int] = Map(apple -> 4, banana -> 2, kiwi -> 1)
Although I’m not an expert in Scala, I know that the language is not lazy (differently from Haskell), so mapValues will produce an intermediate Map, which in turn will be passed as input to filterNot (and so if there were other operations in chain).
How to avoid this useless intermediate data structures?
Note: I understand that the question can be generalized to other data structures. Here I’m using a Map just be cause it’s the data structure that I was using in my real code (although with other data 🙂 )
This seems to do the trick:
When run it produces this output: