The typical academic example is to sum a list. Are there real world examples of the use of fold that will shed light on its utility ?
相关问题
- Relation between Function1 and Reader Monad
- scala passing function with underscore produces a
- Haskell - How to create a mapTree function based o
- Combining n vectors into one vector of n-tuples
- Improve this code by eliminating nested for cycles
相关文章
- Is there something like the threading macro from C
- Learning F#: What books using other programming la
- Creating a list of functions using a loop in R
- When to use interfaces, and when to use higher ord
- Functors in Ocaml
- Java Lambda Referencing Enclosing Object: Replace
- Are 'currying' and 'composition' t
- Control.Parallel compile issue in Haskell
Lots And Lots Of foldLeft Examples lists the following functions:
fold
is perhaps the most fundamental operation on sequences. Asking for its utility is like asking for the utility of afor
loop in an imperative language.Given a list (or array, or tree, or ..), a starting value, and a function, the
fold
operator reduces the list to a single result. It is also the natural catamorphism (destructor) for lists.Any operations that take a list as input, and produce an output after inspecting the elements of the list can be encoded as folds. E.g.
The fold operator is not specific to lists, but can be generalised in a uniform way to ‘regular’ datatypes.
So, as one of the most fundamental operations on a wide variety of data types, it certainly does have some use out there. Being able to recognize when an algorithm can be described as a fold is a useful skill that will lead to cleaner code.
References:
My lame answer is that:
This question reminded me immediately of a talk by Ralf Lämmel Going Bananas (as the rfold operator notation looks like a banana (| and |)). There are quite illustrative examples of mapping recursion to folds and even one fold to the other.
The classic paper (that is quite difficult at first) is Functional Programming with Bananas, Lenses,. Envelopes and Barbed Wire named after the look of other operators.