Consider, I want to implement some function, that would apply Long => T to range of integers a..b and accumulate result of type T (it is exercise, not a search for effective solution)
def sum[T <: Number](f: Long => T)(a: Long, b: Long): T = {
def loop(acc: T, n: Long): T =
if (n > b)
acc
else
loop(acc + f(n), n + 1)
loop(0, a)
}
It flaws at loop(0, complaining
error: type mismatch;
found : Int(0)
required: T
loop(0, a)
I understand why, but what are the options to give 0 of Numeric type T here? If any, of course.
You should use the
Numerictype class for your genericT. This will give you access to methodszeroandplus(since everyNumericmust define these) that will allow you to generically perform a summation.Btw: this is what Scala’s built-in
summethod does: