Skip to content

Instantly share code, notes, and snippets.

@sahiljambhekar
Created August 8, 2018 00:11
Show Gist options
  • Save sahiljambhekar/ad26d01c078b06bc47d25aa2459828de to your computer and use it in GitHub Desktop.
Save sahiljambhekar/ad26d01c078b06bc47d25aa2459828de to your computer and use it in GitHub Desktop.
Playing with Scala Collections
/*
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