1

I have this function that takes two lists and returns the sum of the two lists.

Example:

def sumOfSums(a: List[Int], b: List[Int]): Int = {
  var sum = 0
  for(elem <- a) sum += elem
  for(elem <- b) sum += elem
  sum
}

Simple enough, however now I'm trying to do it recursively and the second list parameter is throwing me off.

What I have so far:

def sumOfSumsRec(a: List[Int], b: List[Int], acc: Int): Int = a match {
  case Nil => acc
  case h :: t  => sumOfSumsRec(t, acc + h)
}

There's 2 problems here:

  1. I'm only matching on the 'a' List
  2. I'm getting an error when I try to do acc + h, im not sure why.

Question: How can I recursively iterate over two lists to get their sum?

1
  • 1
    Can't you merge the lists before the recursion? Also for the second problem, that is because your sumOfSumsRec requires 3 arguments, not 2. Commented Oct 6, 2017 at 7:01

1 Answer 1

2

Pattern match both lists:

import scala.annotation.tailrec

def recSum(a: List[Int], b: List[Int]): Int = {
  @tailrec
  def recSumInternal(a: List[Int], b: List[Int], acc: Int): Int = {
    (a, b) match {
      case (x :: xs, y :: ys) => recSumInternal(xs, ys, x + y + acc)
      case (x :: xs, Nil) => recSumInternal(xs, Nil, x + acc)
      case (Nil, y :: ys) => recSumInternal(Nil, ys, y + acc)
      case _ => acc
    }
  }
  recSumInternal(a, b, 0)
}

Test:

recSum(List(1,2), List(3,4,5))

Yields:

15  

Side note:

For any future readers of this post, I assumed this question was prinarly asked for educational purposes mostly, hence showing how recursion can work on multiple lists, but this is by no mean an idiomatic way to take. For any other purposes, by all means:

scala> val a = List(1,2)
a: List[Int] = List(1, 2)

scala> val b = List(3,4,5)
b: List[Int] = List(3, 4, 5)

scala> a.sum + b.sum
res0: Int = 15

Or consider using mechanisms such as foldLeft, foldMap, etc.

Sign up to request clarification or add additional context in comments.

1 Comment

Amazing! Thanks so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.