如何在Scala中编写限制函数? [英] How to write a limit function in Scala?

查看:93
本文介绍了如何在Scala中编写限制函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



所以这是我的第一个Scala应用程序中的某些错误,后来我发现我的限制函数并没有工作, strong>第一次尝试:

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

它总是返回 x

我的第二次尝试看起来像这样:

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

并且工作正常。



所以我的问题是:为什么第一个例子中的 min; max; 基本上没有操作, x; 不是?
这是我第二次尝试好Scala吗?

解决方案

clamp ),看起来像这样:

  //注意:这仍然会做一些装箱和取消装箱,因为Ordering / Ordered不是@specialized。 
@inline def clamp [@specialized(Int,Double)T:Ordering](value:T,low:T,high:T):T = {
import Ordered._
if (价值低)低其他如果(价值>高)其他价值
}



<在Scala中,表达式的结果是该表达式中提到的最后一个值。 if-expression在第一次尝试中的结果将被丢弃,因为每个if-expression后面跟着另一个表达式。你的第二次尝试是可以的,但你可以用 if ... else 来完成,就像我的例子。你可以这样写:

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


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?

解决方案

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

这篇关于如何在Scala中编写限制函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆