Created
August 8, 2018 00:11
-
-
Save sahiljambhekar/ad26d01c078b06bc47d25aa2459828de to your computer and use it in GitHub Desktop.
Playing with Scala Collections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Inspired from https://commitlogs.com/2016/09/10/scala-fold-foldleft-and-foldright/ | |
*/ | |
/*Find sum of first 10 integers. | |
For the first step: acc will be assigned 0 | |
Thus making the first call (0,1) => 0+1 => 1 which will be assigned back to the acc. | |
Thus making the second call (1,2) => 1+2 => 3 , so on and so fourth. | |
*/ | |
(1 to 10).foldLeft(0)( (acc,currentNumber) => acc + currentNumber ) | |
//or more simply using positional arguments. | |
(1 to 10).foldLeft(0)( _ + _) | |
/*Reversing a list. | |
We can use a ListBuffer as accumulator and keep prepending the `currentChar` to it. | |
*/ | |
import scala.collection.mutable.ListBuffer | |
(1 to 10).foldLeft(ListBuffer[Int]())( | |
(acc,curr) => { | |
acc.+=:(curr) | |
}) | |
//10,9,8.... | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment