简体   繁体   中英

Scala Recursion Over Multiple Lists

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM