Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a limit function in Scala?

After wondering about certain bugs in my first Scala application, I discovered that my limit function was not quite working ... at all!

So here was my first attempt:

  def limit(x : Double, min: Double, max : Double) = {
    if (x < min) min;
    if (x > max) max;
    x;
  }

It always returned x!

My second attempt looked like this:

  def limit(x : Double, min: Double, max : Double) : Double = {
    if (x < min) return min;
    if (x > max) return max;
    x;
  }

and it worked.

So my question: why are min; and max; from the first example basically no-ops, and x; is not? And is my second attempt good Scala?

like image 630
Chris Avatar asked Nov 27 '22 06:11

Chris


2 Answers

Or even:

val limited = lower max x min upper

max and min have the same precedence and associate left, so no parens are needed

like image 133
Nate Nystrom Avatar answered Dec 10 '22 22:12

Nate Nystrom


I've written a generic version of this (which I had called clamp), which looks like this:

// NOTE: This will still do some boxing and unboxing because Ordering / Ordered is not @specialized.
@inline def clamp[@specialized(Int, Double) T : Ordering](value: T, low: T, high: T): T = {
  import Ordered._
  if (value < low) low else if (value > high) high else value
}

In Scala, the result of an expression is the last value mentioned in that expression. The result of the if-expressions in your first attempt is thrown away, because each if-expression is followed by another expression. Your second attempt is ok but you could do it with if ... else like in my example. You could write yours like this:

def limit(x: Double, min: Double, max: Double): Double =
  if (x < min) min else if (x > max) max else x
like image 35
Jesper Avatar answered Dec 10 '22 23:12

Jesper