Skip to content

Commit 935ed30

Browse files
committed
Different ways to sum a list
1 parent 01debf9 commit 935ed30

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.baeldung.scala.listsum
2+
3+
import scala.annotation.tailrec
4+
5+
object SumList {
6+
7+
def sum(list: List[Int]): Int = list.sum
8+
9+
def sumByReduce(list: List[Int]): Int = list.reduceOption(_ + _).getOrElse(0)
10+
11+
def sumByFold(list: List[Int]): Int = list.foldLeft(0)(_ + _)
12+
13+
def sumByIteration(list: List[Int]): Int = {
14+
var sum = 0
15+
list.foreach(num => sum += num)
16+
sum
17+
}
18+
19+
def sumByFor(list: List[Int]): Int = {
20+
var sum = 0
21+
for (num <- list) { sum += num }
22+
sum
23+
}
24+
25+
def sumByTailRecursion(list: List[Int]): Int = {
26+
@tailrec
27+
def rec(list: List[Int], sum: Int): Int = {
28+
list match {
29+
case Nil => sum
30+
case a :: tail => rec(tail, sum + a)
31+
}
32+
}
33+
rec(list, 0)
34+
}
35+
36+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.baeldung.scala.listsum
2+
3+
import org.scalatest.flatspec.AnyFlatSpec
4+
import org.scalatest.matchers.should.Matchers
5+
import org.scalatest.prop.TableDrivenPropertyChecks
6+
7+
class SumListUnitTest
8+
extends AnyFlatSpec
9+
with Matchers
10+
with TableDrivenPropertyChecks {
11+
12+
private val table = Table(
13+
("list", "expected sum"),
14+
(List(1, 2, 3, 4), 10),
15+
(List(0), 0),
16+
(List.empty[Int], 0)
17+
)
18+
19+
private val fns = List(
20+
("sum()", SumList.sum),
21+
("sumByFold()", SumList.sumByFold),
22+
("sumByReduce()", SumList.sumByReduce),
23+
("sumByIteration()", SumList.sumByIteration),
24+
("sumByFor()", SumList.sumByFor),
25+
("sumByTailRecursion()", SumList.sumByTailRecursion),
26+
)
27+
28+
it should "calculate sum for a list" in {
29+
forAll(table) { (input, expected) =>
30+
fns map { (name, fn) =>
31+
withClue(s"sum using the function `${name}` ") {
32+
fn(input) shouldBe expected
33+
}
34+
}
35+
}
36+
}
37+
38+
}

0 commit comments

Comments
 (0)