Skip to content

Commit da49841

Browse files
committed
Fold and Reduce operations example in scala
1 parent 4addb9f commit da49841

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Special_Functions/FoldAndReduce.scala

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* foldLeft and foldRight will perform a reduction operation with a seed value.
3+
* reduceLeft and reduceRight will perform a reduction operation without a seed value.
4+
* Fold and Reduce operations can be applied to List, Set, String, Map, Stream and Options.
5+
**/
6+
object FoldAndReduce extends App
7+
{
8+
//using foldLeft
9+
val foldLeftRes = (1 to 10).foldLeft(0){(total:Int, next:Int) =>
10+
println(s"Total: $total, Next:$next")
11+
total + next}
12+
println("foldLeftRes: " + foldLeftRes + "\n\n")
13+
14+
//using reduceLeft
15+
val reduceLeftRes = (1 to 10).reduceLeft{(total:Int, next:Int) =>
16+
println(s"Total: $total, Next:$next")
17+
total + next}
18+
println("reduceLeftRes: " + reduceLeftRes + "\n\n")
19+
20+
//using foldRight
21+
val foldRightRes = (1 to 10).foldRight(0){(next:Int, total:Int ) =>
22+
println(s"Total: $total, Next:$next")
23+
total + next}
24+
println("foldRightRes: " + foldRightRes + "\n\n")
25+
26+
//using reduceRight
27+
val reduceRightRes = (1 to 10).reduceRight{(next:Int, total:Int ) =>
28+
println(s"Total: $total, Next:$next")
29+
total + next}
30+
println("reduceRightRes: " + reduceRightRes + "\n\n")
31+
32+
//alternatives for above functionalities
33+
println("(1 to 10).sum : " + (1 to 10).sum)
34+
println("(1 to 10).product : " + (1 to 10).product)
35+
36+
//shorthand notation for foldLeft example
37+
println("(1 to 10).foldLeft(0)(_ + _) : " + (1 to 10).foldLeft(0)(_ + _))
38+
println("(1 to 10).mkString(\",\") : " + (1 to 10).mkString(","))
39+
}

0 commit comments

Comments
 (0)