Foldlist
LikeMapandFilter, foldlists are an important part of the list processor's, as well asfunctional programmer'stoolbox. They let you digest a list and create a value that comes from the repeated application of the function on that list.
Folds maybe also called reduce, accumulate, aggregate, compress, or inject depending upon the language.
Unravelling the Mystery
Intuitively, fold is like folding a chain (the list) from one end (left or right) with glue (the function) and producing just a compressed small thing (the output).
A possible example where you want to do is the factorial function.
评估的事实orial of , you want to fold the list of integers from to with the multiplication function.
This actually means something like this:
What we mean by folding the list
[1..n]
with the(*)
function is to apply it repeatedly to two selected elements and then apply the function to the previous result and the third element and so on.
Oh yes,foldl f z L
procedurally can be written like this
1 23 4 |
|
Folding from different sides
In case the operator is not associative, the result certainly depends on the direction in which the fold proceeds.
With the knowledge that every list written in the form[a1, a2, a3... aN]
is just syntactic sugar fora1:a2:a3:...:aN:[]
where[]
is the empty list, the following illustrations should be sufficient to explain the left and right folds.
Note that is the function with which we are folding. is a initialisation value with which folding starts. It is often useful to use an identity element as .
Folding could also take in a tree like fashion that one would define in haskell as follows:
1 23 4 5 6 7 8 9 |
|
The following code nicely illustrates the three kinds of folds:
1 23 4 5 6 7 8 |
|
Examplar Implementations
Haskell
In haskell, we have alreadyfoldl
andfoldr
already defined in the prelude.
Once we have defined have defined
foldt
as above and merge as follows
1 23 4merge[]ys=ysmergexs[]=xsmergexs@(x:xt)ys@(y:yt)|x<=y=x:mergextys|otherwise=y:mergexsyt
we could implementMergeSortthis way:
1 2mergesort::(Orda)=>[a]->[a]mergesortxs=foldtmerge[][[x]|x<-xs]
Python
In python, thereduce
function serves the purpose of fold. Also, the initialization value is not mandatory in python.
One could define the factorial function the following way:
1factorial=lambdan:reduce(lambdaa,b:a*b,xrange(1,n+1))
In Python 3, thereduce
function has been removed from the standard library. One needs toimport functools
to use it.
Ruby
Factorial implementation in Ruby.
1 23 4 5 6 7 8deffactnum(1..num).inject{|acc,i|acc*i}end=beginExample:> fact 36=end