定义接受不同数值类型列表的函数的标量方法 [英] scala way to define functions accepting a List of different numeric types

查看:123
本文介绍了定义接受不同数值类型列表的函数的标量方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:我有一个函数,该函数将List [Double]作为参数,对列表的元素执行一些算术运算,然后返回结果.我也希望该函数接受List [Int].这是一个示例:

I have the following problem: I have a function which takes a List[Double] as parameter, performs some arithmetic operations on the elements of the list and than return the result. I would like the function also to accept List[Int]. Here is an example:

def f(l: List[Double]) = {
    var s = 0.0 
    for (i <- l)
        s += i
    s
}

val l1 = List(1.0, 2.0, 3.0)
val l2 = List(1, 2, 3)

println(f(l1))
println(f(l2))

当然,第二个println失败,因为f需要List [Double]而不是List [Int].

Of course the second println fails since f requires List[Double] and not List[Int].

还要注意f函数内和的非标量形式表示,以证明需要在函数本身内使用0(或其他常量)(如果我求和Int值,则必须将s初始化为0而不是0.0

Also note the non scala style formulation of the sum within the f function in order to evidence the need to use 0 (or other constants) within the function itself (if i sum Int values I have to init s to 0 not 0.0.

哪种方法(较少的代码)是使函数在Double和Int上都能正常工作的最好方法?

Which is the best way (less code) to get the function work on both Double and Int?

(我不太确定如何使用它,所以我已经看过2.8个数字特征了……)

(I have seen something about 2.8 Numeric trait by I'm not so sure how to use it...)

感谢大家的帮助.

推荐答案

在Scala 2.8中,使用数字组合进行隐式转换,您的示例可以写为:

With scala 2.8 and using Numeric combine to implicit conversion your example could be written as :

import Numeric._
def f[T](l: List[T])(implicit n: Numeric[T]):T = {
    var s = n.zero
    for (i <- l)
        s = n.plus(s, i)
    s
}

val l1 = List(1.0, 2.0, 3.0)
val l2 = List(1, 2, 3)

println(f(l1))
println(f(l2))

//or
def f2[T](l: List[T])(implicit n: Numeric[T]):T = {
 import n._
 var s = zero
 for (i <- l)
   s += i
 s
}
println(f2(l1))
println(f2(l2))

现在再看一个示例,以更标量的方式计算总和:

Now another example doing the sum in a more scala way:

def sum[T](l:List[T])(implicit n: Numeric[T]):T = {
 import n._
 l.foldLeft(zero)(_ + _)
}

println(sum(l1))
println(sum(l2))

//or since 2.8 Seq include already a sum function
def sum[T](l:List[T])(implicit n: Numeric[T]):T = l.sum

println(sum(l1))
println(sum(l2))

这篇关于定义接受不同数值类型列表的函数的标量方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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