# Recursive function taking functions as arguments

I'm trying to implement Lie brackets and derivatives of nth order. For doing this, I've stumbled upon something I don't understand. Here is an illustration: First I define the functions:

Operator[f_, g_, x__, opt_] :=
Piecewise[{{f[x], opt == 1}, {Operator[f, g, g[x], 1], opt==2}}]
ff[x__] := {x[], x[]}
gg[x__] := {-x[], -x[]}


Then I ask for these evaluations

Operator[ff, gg, {x1, x2}, 2]
Operator[ff, gg, gg[{x1, x2}], 1]
ff[gg[{x1, x2}]]


The results I found were:

{-x1, -x2}
{-x2, -x1}
{-x2, -x1}


The first result is actually just gg[{x1,x2}], while I wanted it to be the same as the third result ff[gg[{x1,x2}]], and the second result worked as I expected.

Anyone has an idea about this problem? Is there some language detail I don't know? Because the first result simply makes no sense to me right now.

I do not get the same results. If I do

ClearAll[Operator, ff, gg, x1, x2]
Operator[f_, g_, x__, opt_] :=
Piecewise[{{f[x], opt == 1}, {Operator[f, g, g[x], 1], opt == 2}}]
ff[x__] := {x[], x[]}
gg[x__] := {-x[], -x[]}


then

{Operator[ff, gg, {x1, x2}, 2],
Operator[ff, gg, gg[{x1, x2}], 1],
ff[gg[{x1, x2}]]}


-> {{-x2, -x1}, {-x2, -x1}, {-x2, -x1}}

I think the function could then have been defined as

ClearAll[Operator]
Operator[f_, g_, x__, 1] := f[x]
Operator[f_, g_, x__, 2] := f[g[x]]


In which case we also have

{Operator[ff, gg, {x1, x2}, 2],
Operator[ff, gg, gg[{x1, x2}], 1],
ff[gg[{x1, x2}]]}


-> {{-x2, -x1}, {-x2, -x1}, {-x2, -x1}}

• Your answer is right. My exemple was wrong, I got the same output after clearing all variables. However, I couldnt' adapt your alternative to the code for Lie derivative I'm working on: LieD[f_, h_, x__, u__, n_] := Simplify[Piecewise[{ {h[x], n == 0}, {D[h[x], {x}].f[x, u], n == 1}, {LieD[f, LieD[f, h, x, u, 1], x, u, n - 1], n > 1}}]] fe2[x__, u_] := {x[]^2/2 + Exp[x[]]+x[],x[]^2} he2[x__] := x[] LieD[fe2, he2, {x1, x2}, u, 1] LieD[fe2, he2, {x1, x2}, u, 2] May 30, 2013 at 16:16
• @Mefitico I think in your last code it is a bad idea to make the argument pattern like you have made it. Note that two BlankSequences () in row is either ambiguous or at least misleading. In LieD[f_, h_, x__, u__, n_] you have x and u__ in a row. So if I enter LieD[1,2,3,4,5,6,7] then we it is confusing what x and u must be. I think you want to pass lists as arguments, but then you can just use LieD[f_, h_, x_, u_, n_]:=. That is also consistent with your use of Part ([[]]). My advice is to also use fe2[x_,u_]:= and he[x_]:=. I hope that helps, otherwise maybe I can help more. May 30, 2013 at 20:21