Skip to content

Commit a43af08

Browse files
Merge pull request #1595 from yadavan88/sum-list-scala
Different ways to sum a list
2 parents a7dba4a + 0136a80 commit a43af08

File tree

2 files changed

+97
-0
lines changed

2 files changed

+97
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
def sumNumeric[T](list: List[T])(using numeric: Numeric[T]): T = {
37+
list.sum
38+
}
39+
40+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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+
it should "calculate sum for any numeric types" in {
39+
val ints = List(1, 2, 3, 4)
40+
SumList.sumNumeric(ints) shouldBe 10
41+
SumList.sumNumeric(List.empty[Int]) shouldBe 0
42+
43+
val doubles = List(1d, 2d, 3d, 4d)
44+
SumList.sumNumeric(doubles) shouldBe 10d
45+
46+
val bigints = List(BigInt(1), BigInt(2), BigInt(3), BigInt(4))
47+
SumList.sumNumeric(bigints) shouldBe BigInt(10)
48+
49+
}
50+
51+
it should "calculate the sum of inside fields" in {
52+
case class Item(price: Int)
53+
val items = List(Item(1), Item(2), Item(3), Item(4))
54+
items.foldLeft(0)((acc, item) => acc + item.price) shouldBe 10
55+
}
56+
57+
}

0 commit comments

Comments
 (0)