Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
))

1 Answers

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)
like image 101
dk14 Avatar answered May 23 '26 08:05

dk14



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!