# Defining a function with parameters as variables [duplicate]

I have an expression V = (a + a)b. How would I define a function of a, a and b? I'm looking for something like this f[a_,a_,b_]=(a + a)b but Mathematica isn't satisfied with that definition.

• I use a large number of a[i] and b[i] in expressions that are generated in loops in my program.
– user18822
Aug 11, 2014 at 23:40

One way to do this, most likely not the most elegant, is to rename variables of the form a[n] temporarily.

Suppose v = (a + a) b. Then define

f[a1_, a2_, b1_] := Evaluate[v /. {a_[n_] :> ToExpression[ToString[a] <> ToString[n]]}]


With this definition you get the desired result if you evaluate f[a,a,b].

• Be warned that this method will evaluate symbols a1 etc., and expressions a etc. Consider guarding with Block. Aug 12, 2014 at 5:19

Another alternative:

Clear[f, V]
V = (a + a) b;
f[x_, y_, z_] := V /. Thread[Variables[V] :> {x, y, z}];
f[1, 2, 3]
(* 9 *)

ClearAll[f,g];
f[a_, a_, b_] := (a + a) b

f[a, a, b]
(* (a + a) b *)

f[z, z, w]
(* w (z + z) *)

f[z, z, w]
(* f[z, z, w] --- f undefined for this input pattern *)


Or, more generally,

g[a_[x___], a_[y___], b_[z___]] := (a[x] + a[y]) b[z]

g[a, a, b]
(* (a + a) b *)
g[a, a[3, 2], b[1, 2, 3]]
(* (a + a[3, 2]) b[1, 2, 3] *)
g[w, w, z]
(* (w + w) z *)
g[w, w[], z[1, 2, 3]]
(* (w[] + w) z[1, 2, 3] *)
g[w, w, z]
(* g[w, w, z] *)

• Well, but what if one wants to calculate g[1, 2, 3]? Feb 25, 2017 at 4:09
• @xzczd, maybe we can do something like g[arg1 : a_[___] | x_, arg2 : a_[___] | y_, arg3 : b_[___] | z_] := (arg1 + arg2) arg3 but i am not sure this is what what OP asked.
– kglr
Feb 25, 2017 at 4:42

Are you trying to nest functions? i.e. are 'a' and 'b' two functions that you apply the parameter values of '1' or '2' to them and then apply the results to f?

Or in the case that a is simply a name for a variable (something like 'x') Then maybe you're simply looking for f[x_,y_,z_]:=(x+y)z

• a, a,... are variables and not functions, I cannot rename them.
– user18822
Aug 12, 2014 at 0:04
• @Dave84 As this answer suggests, just define f[x_,y_,z_]:=(x+y)z. Then, f[a,a,b] gives what you want. Aug 12, 2014 at 0:31
• @AndyS The problem is that I have an expression saved in some variable V which includes constants and variables a, a, ..., a[i]. I want to define a function f[a_, a_, ..., a[i]_] = V.
– user18822
Aug 12, 2014 at 0:40