Wolfram: Fold (reduce)

By Xah Lee. Date: .

Fold (aka reduce)

Fold

Fold[f, initValue, list]

  • Recurse a function f of 2 parameters, let's call them state item.
  • Each time,
  • state is the last result of f.
  • item is the new item in list.
  • repeat untill no more items. Return the result.
  • initValue is used for state when f starts.

💡 TIP: fold aka reduce, is a general purpose loop in functional programing style.

Fold[f,x,{a,b,c,d}]
(* f[f[f[f[x, a], b], c], d] *)
Fold[f, {a,b,c,d}]
(* f[f[f[a, b], c], d] *)
Fold[f, list]

same as

Fold[f,First[list],Rest[list]]

FoldList

FoldList

Like Fold but return a list of all steps.

FoldList[f, x, {a, b, c}]

(*

{
x,
f[x, a],
f[f[x, a], b],
f[f[f[x, a], b], c]
}

*)

FoldWhile

FoldWhile

Like Fold but with a condition test to stop.

FoldWhile[
Function[{x,y}, x+y] ,
 {1,1,1,1,1,1,1,1,1},
Function[x, UnsameQ[ Mod[ x, 5 ], 0 ]]
 ]
(* 5 *)
FoldWhileList

Like FoldWhile but return a list of all steps.

FoldWhileList[
Function[{x,y}, x+y] ,
 {1,1,1,1,1,1,1,1,1},
Function[x, UnsameQ[ Mod[ x, 5 ], 0 ]]
 ]
(* {1, 2, 3, 4, 5} *)

Wolfram. Loop, Iteration, Recursion