My solution is:
def mySum[T: Numeric](l: List[T]): T = {
val s = implicitly[Numeric[T]].zero
@tailrec
def inner[T: Numeric](l: List[T], s: T): T = l match {
case Nil => s
case h :: t => inner(t, implicitly[Numeric[T]].plus(s, h))
}
inner(l, s)
}
This works perfect and accepts any Numeric type for sum.
However, the following code can't compile, can you figure out why? Hint: Desugar the code first.
@tailrec
def mySum[T: Numeric](l: List[T], s: T = implicitly[Numeric[T]].zero): T = l match {
case Nil => s
case h :: t => mySum(t, implicitly[Numeric[T]].plus(s, h))
}
Notes: This is only for practice, the Scala version of sum which use foldLeft is safe to use.