3 ms·
I guess a short explanation is in order. foldr/foldl are folding or reduction operations. Heard of MapReduce? Well, fold is the reduction part (foldl specifical
by nickb 18y ago
I guess a short explanation is in order. foldr/foldl are folding or reduction operations. Heard of MapReduce? Well, fold is the reduction part (foldl specifically). It takes a list, function, and an accumulator and returns a list and the final accumulator value as a result. Pretty much every functional language has one and foldr/foldl names come from S/ML and later from Haskell.
You can see an example here: http://www.cse.unsw.edu.au/~en1000/haskell/hof.html http://www.cse.unsw.edu.au/~en1000/haskell/hof.html
The difference between foldr and foldl is how the list is processed and in the final list (left to right or right to left) so depending on what your function is, order does matter. Also, foldr is not tail recursive so it can't be optimized nicely.
These sorts of constructs are coming back to forefront of computing since they offer us a very efficient way to do distributed computing. I use MR all the time these days to deal with large data sets.
- lpgauth 18y agoThat's weird.. I just had an SML class and we never learned it was call folding... It was just being recursive on a list. Also, the way the website is made the list seems to be infinite (stream) which is impossible in SML only in Haskell.
- eru 18y agoRegarding tail-recursion and optimization: In Haskell I guess it is the other way round - foldr is the more 'natural' function when you consider lazy evaluation.