Scala Fold Examples
Last updated:View all code examples on this jupyter notebook
fold | foldLeft | foldRight | |
---|---|---|---|
Order of appplication |
Applied in no particular order, so the function needs to be commutative | Applied from left to right | Applied from right to left |
fold
.fold(initialState)((anElement, anotherElement) => newState)
Apply the given function to the initial state and all collection elements:
Example: sum numbers in collection, with initial state of 2
val seq = Seq(1,2,3)
seq.fold(2)((elem1, elem2) => a+b)
// res: Int = 8
foldLeft
.foldLeft(initialState)((currentState, currentElement) => newState)
Apply the given function to the initial state and all collection elements, starting from left to right
Example: sum numbers in collection
val seq = Seq(1,2,3)
// accum is short for "accumulator"
seq.foldLeft(0)((accum, elem) => accum + elem)
// res: Int = 6
foldLeft, state with different types
.foldLeft(initialState)((currentState, currentElement) => newState)
The state you keep doesn't need to be of the same type as the collection elements:
Example: sum the lengths of strings in collection
val seq = Seq("foo", "bar", "baz")
// accum is short for "accumulator"
seq.foldLeft(0)((accum, elem) => accum + elem.size)
// res: Int = 9
foldLeft, string concat
.foldLeft(initialState)((currentState, currentElement) => newState)
foldleft
is frequently used to concatenate strings into a single string
val seq = Seq("foo", "bar", "baz")
// accum is short for "accumulator"
seq.foldLeft("")((accum, elem) => accum + elem)
// res: String = "foobarbaz"
foldRight
.foldRight(initialState)((element, currentState) => newState))
Same as foldLeft
but the collection is traversed from right to left and the order of the parameters in the passed function is inversed: (elem, accum)
instead of (accum, elem)
Example concatenate strings from right to left
val seq = Seq("foo", "bar", "baz")
// accum is short for "accumulator"
seq.foldRight("")((elem, accum) => accum + elem)
//res: String = "bazbarfoo"
Fold vs Reduce
fold | reduce | |
---|---|---|
Order of appplication |
foldLeft and foldRight variants | reduceLeft and reduceRight variants |
State type | State can be of any type | State must be of the same type as the elements |