user4727396
user4727396

Reputation:

How to access current mapped tuple while mapping a list?

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

Answers (3)

Didier Dupont
Didier Dupont

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

dk14
dk14

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

Marth
Marth

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

Related Questions