Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expressing square in Scala

Tags:

scala

For some reason (that escapes me), Scala math library does not have a pow-function for integers, but only for Doubles.

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?

like image 215
akauppi Avatar asked Dec 03 '12 18:12

akauppi


2 Answers

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.

like image 64
Rex Kerr Avatar answered Nov 02 '22 22:11

Rex Kerr


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
like image 16
idonnie Avatar answered Nov 02 '22 22:11

idonnie