2

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?

sma11s101
  • 21
  • 1

2 Answers2

4

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.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
2
  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.
Alan
  • 13,686
  • 19
  • 38