Idiom to "map" a single val?


#1

Is there an idiom to use a val in a computation twice, without having to create a new intermediate val?

That is, if map() somehow worked on non-collections, it would be nice to be able to do:

3.map(x => Math.pow(x,x))

The closest I’ve come to on my own is:

List(3).map(x => Math.pow(x,x)).apply(0)


#2

Hi,

It’s very easy to add this operator in your own code through an implicit conversion.

By the way, thanks for adding credibility to my previous statement that “many people would like to have [this operator] in the standard library” :sweat_smile:


#3

You can do:

Welcome to Scala 2.12.4 (OpenJDK 64-Bit Server VM, Java 1.8.0_151).Type in
expressions for evaluation. Or try :help.scala> ((x: Int) => Math.pow(x,
x)).apply(3)res1: Double = 27.0


#4

A method is the best way to avoid an intermediate allocation:

def xPowX(x: Double): Double = Math.pow(x, x)
xPowX(3.0)

Everything else will result in some allocation, e.g. the ‘map’ will allocate a function that applies the operation.


#5

Thanks! That keyword “pipe” helped a lot, and I found and ended up using this code:

https://www.scala-academy.com/tutorials/scala-pipe-operator-tutorial