WolframLang: Recursion

By Xah Lee. Date: . Last updated: .

Recursion of function with 1 arg

Nest

Recursion of a function n times.

Nest

Nest[f, x, 3] === f[f[f[x]]]
NestList

Like Nest but return a list of all steps.

NestList

NestList[f, x, 3] === {x, f[x], f[f[x]], f[f[f[x]]]}

Conditional Stop

NestWhile

Like Nest, but with a condition when to stop.

NestWhile has a lot options, controlling when to stop, what arguments to feed to the test function. See documentation.

NestWhile

NestWhile[ Function[{x}, x + 1], 1, Function[Mod[#, 5] =!= 0] ]
(* 5 *)
NestWhileList

Like NestWhile but return a list of all steps.

NestWhileList

NestWhileList[ Function[{x}, x + 1] , 1, Function[Mod[#, 5] =!=  0] ]
(* {1, 2, 3, 4, 5} *)

Stop when result is the same

FixedPoint

Recursion of a function until result no longer changes. Optionally with a max number of steps.

FixedPoint

see real life examples:

FixedPointList

Like FixedPoint but return a list of all steps.

FixedPointList

Recursion of function with 2 args

Fold

Similar to reduce in JS: Array.prototype.reduce .

Fold

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

Like Fold but return a list of all steps.

FoldList

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

(*

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

*)

Conditional Stop

FoldWhile

Like Fold but with a condition test to stop.

FoldWhile

FoldWhileList

Like FoldWhile but return a list of all steps.

FoldWhileList

FoldWhileList[
 Function[# + #2],
 {1,1,1,1,1,1,1,1,1},
 Function[ UnsameQ[ Mod[ #, 5 ], 0 ]] ]

(* {1, 2, 3, 4, 5} *)

WolframLang Loop, Iteration, Recursion