3
$\begingroup$

I need to find the nthComposition of a function. I thought there could be something like nthComposition[f,x,5] means five times composition of f with x as input parameter. I don't want to repeat f in my code as there is no fixed number for my composition, it could change every time. Assume it is my function:

f [va_] := ( va*2);

Composition[f, f][s]
4 s

Composition[f, f, f][s]
8 s
$\endgroup$
1

3 Answers 3

5
$\begingroup$

Depending on exactly how you want to use this, you might want to bundle this up into its own function (or function overload).

f[nestLevel_, va_] := Nest[f, va, nestLevel]

or

compf[nestLevel_] := Composition @@ ConstantArray[f, nestLevel]

Usage:

f[2, x]
(* f[f[x]] *)
(* or 4 x using your sample function *)

compf[3]
(* f@*f@*f *)

compf[3][x]
(* f[f[f[x]]] *)
(* or 8 x using your sample function*)
$\endgroup$
2
  • $\begingroup$ thanks but I'm a bit confused about the first solution : f[nestLevel_, va_] := Nest[f, va, nestLevel] . we are defining f on left side but giving it to Nest as input on right side. how it doesn't show any conflict? $\endgroup$
    – Azzurro94
    Jun 6 at 14:55
  • 1
    $\begingroup$ f is just a symbol. We're not defining f directly, so to speak, we're specifying DownValues (replacement rules for a particular form). There is no infinite recursion, because once the Nest has been performed, we have forms with f that have only a single argument. So, the evaluator will use the one-argument definition to resolve those (if it exists). You could make this more explicit/safe if you define a new function instead of overloading f: nestf[nestLevel_, va_] := Nest[f, va, nestLevel]. $\endgroup$
    – lericr
    Jun 6 at 15:21
4
$\begingroup$

As answered well in the comment, we can find it by

Nest[f, x, 5] 
$\endgroup$
3
$\begingroup$
Clear["Global`*"]

For some functions f, you can use NestList and FindSequenceFunction to solve the problem more generally

f[va_] := (va*2);

seq = Rest@NestList[f, x, 6]

(* {2 x, 4 x, 8 x, 16 x, 32 x, 64 x} *)

Clear[f]

f[x_, n_ : 1] = FindSequenceFunction[seq, n]

(* 2^n x *)

f[s]

(* 2 s *)

f[s, 5]

(* 32 s *)

f[s, n]

(* 2^n s *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.