Can someone provide some examples for how
Actually get used? I assume they’re shortcuts to the reduce / fold methods, but there’s no examples on how they actually get used in the Scala docs, and they’re impossible to google / search for on StackOverflow.
/:is a synonym forfoldLeftand:\forfoldRight.But remember that
:makes/:apply to the object to the right of it.Assuming you know that
(_ * _)is an anonymous function that’s equivalent to(a, b) => a * b, and the signature of foldLeft and foldRight arei.e. they’re curried functions taking a start value and a function combining the start value / accumulator with an item from the list, some examples are:
which is the same as
And
in infix notation is
which is the same as
Add your own collections and functions and enjoy!
The thing to remember with the short (
/:and:\) notations is that, because you’re using the infix notations you need to put parentheses around the first part in order for it to pick up the second argument list properly. Also, remember that the functions for foldLeft and foldRight are the opposite way round, but it makes sense if you’re visualising the fold in your head.