Mathematica Programming » Functional Programming

Fold / FoldList

Where Nest applies a function in to the result of the previous function call in a nested fashion, Fold and its related functions apply a function to the previous function call and simultaneously map over a list.

As a very simple example we can turn an expression like this:

 c[a1,a2,a3,...,an]

into one like

 c[a1][a2][a3][...][an]

in one line of code. This process is closely related to the concept “currying” in standard functional programming so we can call this pseudocurrying (in fact this example comes directly from a question I asked on the Mathematica stack exchange):

 curry=
Function[expr,
 Replace[expr,h_[a__]:>Fold[#1[#2]&,{h,a}]],
 HoldFirst];

where we take advantage of Mathematica’s ability to set attributes on pure functions. We can use this to, for example, drill into nested associations, where we will also build our association using Fold :

 data=Association@Fold[#2Replace[#,_Rule->Association@#]&,Range[1,10]]
 10987654321

curry@data[10,9,8]
 7654321

Note that Mathematica already implements this type currying for associations:

 data[10,9,8]
 7654321

But for other user-defined types this can be incredibly useful