For some reason (that escapes me), Scala math
library does not have a pow
-function for integers, but only for Double
s.
I need a square function for integers and was figuring what might be the usual way to do this in Scala.
object TestX extends App {
def pow2(v: Int)= v*v
//class MyRichInt( val v: Int ) {
// def ² : Int = v*v // says: "illegal character" for UTF-8 power-of-two
//}
println( pow2(42) )
//println( 42² )
println( math.pow(42,2).toInt )
}
I was surprised to see that the '²' character is not liked by Scala. Maybe it's taken to be a number? Usually all kinds of weird Unicode values are valid and using 42² in code would, indeed, be fancy.
Never mind. Should I shut up and just start using my own pow2
function?
Yes, use your own pow2
. If you need higher powers, you probably won't have room in an Int
anyway. Consider using BigInt.pow
:
scala> BigInt(40).pow(40)
res0: scala.math.BigInt = 12089258196146291747061760000000000000000000000000000000000000000
Of course, if you need not N2 but 2N, just use shifts. (1 << k
= 2k) These work with BigInt
also.
Use backticks for Unicode characters, and implicit classes (Scala 2.10) to add operation on arbitrary types:
implicit class PowerInt(i: Int) {
def `²`: Int = i * i
}
Usage:
3 `²`
Result:
9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With