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$ closely related: Enforcing correct variable bindings, 11461 $\endgroup$ Commented Sep 22, 2016 at 5:36
  • $\begingroup$ even closer: 69590 $\endgroup$ Commented Sep 22, 2016 at 5:49
  • $\begingroup$ 91319, 42691 $\endgroup$ Commented Sep 22, 2016 at 5:55
  • $\begingroup$ Is this your goal at the end? mathematica.stackexchange.com/q/14310/5478 $\endgroup$ Commented Sep 22, 2016 at 5:58

2 Answers 2

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$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.