Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a Scala program to find the sum of the elements of an Int List.
We can achieve this using foldLeft or reduceLeft methods.
- foldLeft() method accepts an initial value and a function to determine how to return the value.
- reduceLeft() method accepts only a function to determine how to return the value.
Let’s look at the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.clearurdoubt object SumOfListElements extends App { val input = List(7, 9, 3, -5, 10, 2) // using reduceLeft val sumByReduceLeft = input reduceLeft (_ + _) println("Sum by ReduceLeft: " + sumByReduceLeft) // using foldLeftLeft val sumByFoldLeft = input.foldLeft(0)(_ + _) println("Sum by FoldLeft: " + sumByFoldLeft) } |
Output:
Happy learning.
Please leave a reply in case of any queries.