Reputation:
Could someone please help me to avoid duplicate computations in the Scala mapping below?
(for (i <- 0 to 20) yield i).map((i: Int) => (
math.pow(2, i),
math.pow(2, i).toString, // duplicate computation
math.sqrt(i),
math.sqrt(i).toString // duplicate computation
))
Upvotes: 3
Views: 88
Reputation: 29528
Just to complement the other answers, which are fine, you can declare vals at will within any block, so :
(1 to 20) map { i =>
val pow2 = math.pow(2,i)
val sqrti = math.sqrt(i)
(pow2, pow2.toString, sqrti, sqrti.toString)
}
the for
will be expanded to exactly that and is probably more pleasant, but it might be useful to know that you can do the same in an anonymous function block as in another block.
Upvotes: 0
Reputation: 22374
You don't need the map
here and you can introduce new values inside for-comprehension:
for {
i <- 0 to 20
pow2 = math.pow(2, i)
sqrti = math.sqrt(i)
} yield (pow2, pow2.toString, sqrti, sqrti.toString)
Upvotes: 3
Reputation: 24802
Not the shortest answer, but what seems the easiest to understand to me: define a method and use it inside the .map
:
def powAndSqrt(i:Int) = {
val pow = math.pow(2,i)
val sqrt = math.sqrt(i)
(pow, pow.toString, sqrt, sqrt.toString)
}
(0 to 20).map(powAndSqrt)
Upvotes: 1