Scala:避免的最佳方法多次在不同的匹配案例

时间:2016-05-26 00:53:58

标签: scala

我想找到表格中一行中所有值的最小值(可能有空值,列可能是不同的类型 - Int,Long,Double,Boolean)。

函数的返回类型取决于输入列,如果all都是Int,则返回类型应为Int。如果混合不同类型,则加倍等等。

我知道returnType会是什么。

方法就像:

 def findMin(args: List[Any]): Any =

一种可能的解决方案可能是:

returnType match {
  case IntType =>
     minValInt = Int.Min
     for(args){
        check for not null 
        for(arg <- args) {
          temp: Int  = arg match {
             case x: Int => x
             case x: Boolean => convert to Int              
          }
        minValInt = min(minValInt, temp)
        return minValInt

  case LongType =>
     minValLong = Long.Min
     for(args){
       check for not null -> minValLong = min(minValLong, arg) (some restrictions while using the arg value directly)
     }
     return minValLong

  case DoubleType =>
     minValDouble = Double.Min
     for(arg <- args){
       check for not null 
       temp: Double = arg match {
          case x: Int => convert to double 
          case x: Long => convert to double (some restrictions while converting)
          case x: Double => x
          case x: Boolean => convert to double
       }
       minValDouble = min(minValDouble, temp)
     }
     return minValDouble
}

这可以在单个匹配案例或更好的事情中完成吗?#34;更整洁&#34;?

2 个答案:

答案 0 :(得分:1)

或许这样的事情?

<?php
    echo '<footer class="footer">
              <div class="container">
                  <p class="text-muted"><a href="contactus.html">Contact Us</a></p>
                  <p class="text-muted"> Copyright &copy;     <span id="yearfooter"> </span>. All rights reserved.     </p>
</div>
          </footer>';
?>

答案 1 :(得分:0)

除了我对用例缺乏想象力之外,您已经将函数类型定义为List [Any] - &gt;你的问题中的任何一个。

所以你有效地告诉编译器什么是期望的,并且失去了使用静态类型系统的优势。

请注意,使用静态类型的函数式编程是关于定义输入域并在编译时将其映射到输出域。 因此返回Int的函数与返回Long或返回Double的函数不同。因此,要么它们是不同的函数,要么将输出域定义为所有可能返回类型的公共超类型,从而丢失特定的信息。

关于显示的代码,似乎返回类型是Int,Long,Double中的任何一个,具体取决于返回最小值所需的最大精度。

由于Int适合Long并且都适合Double,为什么不将Double声明为保证的最大精度返回类型?

因此该函数的类型为List [Any] - &gt;加倍,使程序的其余部分在编译时特定是类型安全吗?