Skip to content

Instantly share code, notes, and snippets.

@yingy4
Last active February 8, 2018 04:01
Show Gist options
  • Save yingy4/37982dcfd0d22d3fe5610bd4bc4aa076 to your computer and use it in GitHub Desktop.
Save yingy4/37982dcfd0d22d3fe5610bd4bc4aa076 to your computer and use it in GitHub Desktop.
Scala A More General Sum Using Tail Recursion

Scala A More General Sum Using Tail Recursion

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment