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))
Of course the second println fails since f requires List[Double] and not List[Int].
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.
Which is the best way (less code) to get the function work on both Double and Int?
(I have seen something about 2.8 Numeric trait by I'm not so sure how to use it...)
Thanks everybody for the help.
def sum[T : Numeric](l:List[T]) = l.sum
will do. – Coffelt