How to write a limit function in Scala?

After thinking about some errors in my first Scala application, I found that my restriction function didn’t quite work ... in general!

So here is my first attempt :

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

He always came back 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 he worked.

So my question is: why min;, max;from the first example, are there no-ops in principle, but x;no? And my second attempt is a good Scala?

+3
source share
4 answers

I wrote a generic version of this (which I named clamp) that 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
}

Scala , . if- , if- . , if ... else, . :

def limit(x: Double, min: Double, max: Double): Double =
  if (x < min) min else if (x > max) max else x
+8

:

val limited = lower max x min upper

max min ,

+12

return, . - x;, . , if/else if/else:

def limit(x : Double, min: Double, max : Double) = 
    if (x < min) min
    else if (x > max) max
    else x

if/else if/else , .

You can also use pattern matching (this is also one expression):

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

I do not think that your second example can be called a "good scala". In such a simple case, it just complicates all this and has three return points (instead of a single return point). It also adds more unnecessary template.

+7
source

Why not just:

import math.{min, max}
val limited = min(max(lower, x), upper)

or

val limited = (lower max x) min upper
+3
source

All Articles