Augmented function of function

I have two generic functions :

ucdu[x : {__}] := Times @@ (x)


and

cb[x : {__}, p : {__}] := Plus @@ (x p)


For instance, they can be applied to vectors in $\mathbb{R}^3$

nv = 3;
xx = Table[Subscript[x, i], {i, 1, nv}](*{Subscript[x, 1], ...., Subscript[x, nv]}*);
pp = Table[Subscript[p, i], {i, 1, nv}](*{Subscript[p, 1], ...., Subscript[p, nv]}*);
ucdu[xx]
cb[xx, pp]


which give :

$x_1 x_2 x_3$ and $x_1 p_1+ x_2 p_2 + x_3 p_3$

Now, I want to write a new function, say a Lagrangian, with one more variable say $\mathcal{L}[xx, pp, \lambda] = ucdu[xx]- \lambda (cb[xx, pp]- R)$. $\mathcal{L}$ must be generic enough to be called on other functions --- for instance, $ucdg[xx,\alpha\alpha]$...

I have tried

ll[u_Symbol, cb_Symbol, λ_, xx_, pp_] := u - λ (cb - R)


but ll[ucdu[xx], cb[xx, pp], λ] returns $ll[x_1 x_2 x_3, x_1 p_1 + x_2 p_2+ x_3 p_3, \lambda,\{x_1, x_2, x_3\},\{p_1, p_2, p_3\}]$ not $x_1 x_2 x_3 - \lambda(-R + x_1 p_1 + x_2 p_2+ x_3 p_3)$

What am I doing wrong? Later I want to write the Gradient with respect of Join[xx,{\lambda}]

• Well, for one you are not calling your function ll with enough arguments. If you define it to take five arguments, of course it will return unevaluated if you call it with three. Also, notice that the return value of ucdu[xx] has head Times, so it won't match the _Symbol pattern restriction you put in the definition. If you redefine ll without the pattern restrictions, and include any expression for xx_ and pp_ (their value doesn't seem to matter, since you don't use them in the definition of ll), then it will evaluate. Whether the return value is correct though, I am not sure. – MarcoB Feb 6 '17 at 16:55
• You might also be interested in How can I implement the method of Lagrange multipliers?. – MarcoB Feb 6 '17 at 17:16

With your function definitions in place, and using indexed variables rather than subscripts:

nv = 3;
xx = Table[x[i], {i, 1, nv}];
pp = Table[p[i], {i, 1, nv}];

Clear[ll]
ll[f_, g_, xvar_, pvar_, lambda_] := f[xvar] - lambda (g[xvar, pvar] - r)

ll[ucdu, cb, xx, pp, lambda]

(* Out: x[1] x[2] x[3] - lambda (-r + p[1] x[1] + p[2] x[2] + p[3] x[3]) *)


That seems to be your intended result.

• MarcoB Thanks. It works also with indexes. – cyrille.piatecki Feb 6 '17 at 18:21
ClearAll[ll2]
ll2[u_, cb_,  λ_] := u - λ(cb - r)

ll2[ucdu[xx], cb[xx, pp], λ]