Skip to content

Commit 1eff836

Browse files
add code for difference between reduce, scan and fold article (#772)
1 parent dda9cd0 commit 1eff836

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package com.baeldung.scala.highorderfunctions
2+
3+
import org.scalatest.flatspec.AnyFlatSpec
4+
import org.scalatest.matchers.should.Matchers
5+
6+
class HighOrderFunctionsUnitTest extends AnyFlatSpec with Matchers {
7+
8+
"reduceLeft" should "calculate the sum correctly" in {
9+
val numbers = List(1, 2, 3, 4, 5)
10+
val actualSum = numbers.reduceLeft(_ + _)
11+
// op: 1 + 2 = 3
12+
// op: 3 + 3 = 6
13+
// op: 6 + 4 = 10
14+
// op: 10 + 5 = 15
15+
// res: Int = 15
16+
assert(15 == actualSum)
17+
}
18+
19+
"reduceLeft" should "concatenate strings correctly" in {
20+
val alphabets = List("A", "B", "C", "D", "E")
21+
val actualResult = alphabets.reduceLeft(_ + _)
22+
assert("ABCDE" == actualResult)
23+
}
24+
25+
"reduceLeft" should "find the largest number correctly" in {
26+
val numbers = List(10, 22, 5, 71, 43)
27+
val actualResult = numbers.reduceLeft(_ max _)
28+
assert(71 == actualResult)
29+
}
30+
31+
"reduceRight" should "calculate the sum correctly" in {
32+
val numbers = List(1, 2, 3, 4, 5)
33+
val actualSum = numbers.reduceRight(_ + _)
34+
// op: 5 + 4 = 9
35+
// op: 9 + 3 = 12
36+
// op: 12 + 2 = 14
37+
// op: 14 + 1 = 15
38+
// res: Int = 15
39+
assert(15 == actualSum)
40+
}
41+
42+
"foldLeft" should "calculate the sum correctly" in {
43+
val numbers = List(1, 2, 3, 4, 5)
44+
val actualSum = numbers.foldLeft(5)(_ + _)
45+
// op: 5 + 1 = 6
46+
// op: 6 + 2 = 8
47+
// op: 8 + 3 = 11
48+
// op: 11 + 4 = 15
49+
// op: 15 + 5 = 20
50+
// res: Int = 20
51+
assert(20 == actualSum)
52+
}
53+
54+
"foldRight" should "concatenate the strings correctly" in {
55+
val alphabets = List("A", "B", "C", "D", "E")
56+
val actualResult = alphabets.foldRight("$")(_ + _)
57+
// op: E + $ = E$
58+
// op: D + E$ = DE$
59+
// op: C + DE$ = CDE$
60+
// op: B + CDE$ = BCDE$
61+
// op: A + BCDE$ = ABCDE$
62+
// res: String = ABCDE$
63+
assert("ABCDE$" == actualResult)
64+
}
65+
66+
"scanLeft" should "have correct intermediate states" in {
67+
val numbers = List(1, 2, 3, 4, 5)
68+
val actualResult = numbers.scanLeft(1)(_ + _)
69+
assert(List(1, 2, 4, 7, 11, 16) == actualResult)
70+
}
71+
72+
"scanRight" should "have correct intermediate states" in {
73+
val numbers = List(1, 2, 3, 4, 5)
74+
val actualResult = numbers.scanRight(1)(_ + _)
75+
assert(List(16, 15, 13, 10, 6, 1) == actualResult)
76+
}
77+
}

0 commit comments

Comments
 (0)