1

How could I define a function that references other values?

eg

a = 2 x; b = 4 k;
f[k_, x_] := a^b
martin
  • 8,678
  • 4
  • 23
  • 70

1 Answers1

3

For reasons explained here, I would strongly advise against using this kind of constructs, which in essence use global variables. However, if you must do this, here is one easy way:

ClearAll[a, b, x, k, f];
a = 2 x; b = 4 k;
f[k_, x_] =  a^b

that is, use Set instead of SetDelayed - in which case your r.h.s. will be computed at the time of the assignment.

Here is another method, which might be somewhat safer:

ClearAll[a, b, x, k, f];
a = 2 x; b = 4 k;
f[kk_, xx_] := Block[{x = xx, k = kk}, a^b]

that is, use Block to dynamically localize x and k, then call your code (a^b here).

But again, the best (safest) way is to make all functions (a and b here) explicitly take the parameters, and pass the parameters explicitly (as explained in the link I gave).

Leonid Shifrin
  • 114,335
  • 15
  • 329
  • 420
  • @ Leonid Shifrin, thank you for your answer - it is not absolutely necessary for me, so I think I will take your advice & keep it all within the function definition itself (though it is rather long!) - but it is good to know that there is a way - again, many thanks for your help on this - I will have a look at the link you provided to understand better the technical aspects. – martin Dec 17 '13 at 19:44
  • @martin - section 4.5 here has a nice explanation of Block. – Chris Degnen Dec 17 '13 at 20:12