4
$\begingroup$

I have the following code

Module[{f,x=0},
f[t_] := x + t;
..........;
...f[1]...;
..........;
]

My aim is to put the declaration of the function f outside the module.

$\endgroup$
  • 4
    $\begingroup$ Don't put f as a Module variable? $\endgroup$ – Rojo Sep 19 '13 at 14:38
  • 2
    $\begingroup$ You could pass x to f as a parameter. $\endgroup$ – Niki Estner Sep 19 '13 at 15:03
  • 1
    $\begingroup$ Or, if you don't want pass x to f, you could use currying: declare a global function makeF that takes a parameter x and returns a new function f. Then use f=makeF[x]; inside the module where you want to use f. $\endgroup$ – Niki Estner Sep 19 '13 at 15:19
  • 2
    $\begingroup$ I see. Mathematica will create a copy of x anyway even with the attributes when you do xx+t, even if you save it back to xx, so in that regard you won't save time. But it's true that you need the attribute to pass by reference and change x from inside f $\endgroup$ – Rojo Sep 19 '13 at 20:56
  • 1
    $\begingroup$ @Rojo Just to make sure I understand Mathematica's memory handling correctly: In the pass-by-value case, if the passed expression is not "changed" in the function (e.g. you only extract parts of the expression by Part[xx,1] and process that further), no copy is created, right? In other words, just the fact that you pass an expression by-value does not mean you use more memory... $\endgroup$ – sebhofer Sep 20 '13 at 19:23
7
$\begingroup$

Passing by reference:

Attributes[f] = HoldFirst;
f[x_Symbol, t_] := x + t;

Module[{x = 0},
 f[x, 1]
 ]

Ref: http://dev.ragfield.com/2009/03/mathematica-call-by-reference.html

$\endgroup$
2
$\begingroup$

I just found an alternative small trick, which imitates the declaration of an inline function and solves the question:

f[x_Symbol, t_] := x + t;

temp = Hold[Module[{x = 0},
                f[x, 1]
           ]] /. DownValues[f]

ReleaseHold[temp]
$\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.