Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Datatype for numeric real range

Tags:

scala

Is there some idiomatic scala type to limit a floating point value to a given float range that is defined by a upper an lower bound?

Concrete i want to have a float type that is only allowed to have values between 0.0 and 1.0.

More concrete i am about to write a function that takes a Int and another function that maps this Int to the range between 0.0 and 1.0, in pseudo-scala:

def foo(x : Int, f : (Int => {0.0,...,1.0})) {
    // ....
}

Already searched the boards, but found nothing appropriate. some implicit-magic or custom typedef would be also ok for me.

like image 910
the dude Avatar asked May 16 '13 12:05

the dude


People also ask

How big is an integer in Scala?

An Integer is a 32-bit value and is central to any numeric representation in Scala. The Long and Short types are similar to Integer.

What are decimal types in Scala?

Scala Numeric Types Numeric type in Scala deals with all types that are stored in numerical. The data type that is used is decimals (float and Double) and integers (Int, Short, Long).


1 Answers

You can use value classes as pointed by mhs:

case class Prob private( val x: Double ) extends AnyVal {
  def *( that: Prob ) = Prob( this.x * that.x )
  def opposite = Prob( 1-x )
}

object Prob {
  def make( x: Double ) = 
    if( x >=0 && x <= 1 ) 
      Prob(x) 
    else 
      throw new RuntimeException( "X must be between 0 and 1" )
}

They must be created using the factory method in the companion object, which will check that the range is correct:

scala> val x = Prob.make(0.5)
x: Prob = Prob(0.5)

scala> val y = Prob.make(1.1)
java.lang.RuntimeException: X must be between 0 and 1

However using operations that will never produce a number outside the range will not require validity check. For instance * or opposite.

like image 193
paradigmatic Avatar answered Sep 19 '22 15:09

paradigmatic