In functional programming, fold (also termed reduce, accumulate, aggregate, compress, or inject) refers to a family of higher-order functions that analyze a recursive data structure and through use of a given combining operation, recombine the results of recursively processing its constituent parts, building up a return value. Typically, a fold is presented with a combining function, a top node of a data structure, and possibly some default values to be used under certain conditions. The fold then proceeds to combine elements of the data structure's hierarchy, using the function in a systematic way.
Go is supposed to be simple
In practice, it is convenient and natural to have an initial value
Reduce, programmers from other languages understand the intent too.
SumAllTailsnow describe the behaviour of their computations as the functions declared on their first lines respectively. The act of running the computation on the collection is abstracted away in
Reduce. If we relied on Go's default value of 0 for
int, we'd multiply our initial value by 0, and then the following ones, so you'd only ever get 0. By setting it to 1, the first element in the slice will stay the same, and the rest will multiply by the next elements.
In mathematics, an identity element, or neutral element, of a binary operation operating on a set is an element of the set which leaves unchanged every element of the set when the operation is applied.
1 + 0 = 1
1 * 1 = 1
Transactionand we wanted a function that would take them, plus a name to figure out their bank balance.
Reduceto make it work. We won't have to change the function body, and we won't have to change any of our existing callers.
Reduce. This allows people to
Reducefrom a collection of
B. In our case from
Reducemore general-purpose and reusable, and still type-safe. If you try and run the tests again they should compile, and pass.
NewBalanceForfeels more declarative, describing what happens, rather than how. Often when we're reading code, we're darting through lots of files, and we're trying to understand what is happening, rather than how, and this style of code facilitates this well.
applyTransactionwithout worrying about loops and mutating state;
Reducetakes care of that separately.
Fold). It's a common pattern for a reason, it's not just for arithmetic or string concatenation. Try a few other applications.
color.RGBAinto a single colour?
Findfunctions for each type of collection you want to search, instead re-use or write a
Findfunction. If you understood the
Reducefunction above, writing a
Findfunction will be trivial.
Aand converts them to
B? Don't call it
Map. Using the "proper" name for these items will reduce the cognitive burden for others and make it more search engine friendly to learn more.
This is not idiomatic