2
$\begingroup$

I'm having trouble defining a function where I previously treated a variable as a parameter. See the following example:

var := 2*a
f[a_] := var

Then f[a] returns 2a but f[2] only returns f[2] without evaluation. I understand I could just define var as a function of a but this is unwieldy for the number of parameters I am using. Is there a function that will 'dereference' var?

$\endgroup$
4
$\begingroup$

I don't know what you are trying to accomplish, but you should be aware that, given your definitions, the argument of f has no effect on the value of f when f[...] is evaluated. Only the value of a in the current scope of f matters.

var := 2 a
f[a_] := var

Clear[a]; x = 0; f[x]

2 a

a = 42; x = 0; f[x]

84

You may as well write

f := var

or forget f altogether.

P.S. Mathematica's scoping rules not at all much like those of C or Java.

$\endgroup$
2
$\begingroup$
  1. From your description it looks like you included an underscore in your definition above that you left out when testing.
  2. I suppose what you are looking for is f[a_] := Evaluate[var]
  3. This is a horrific design and will sooner or later produce problems. Good luck.
$\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.