# How to declare a function that uses local variables of a module outside this module?

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.

• Don't put f as a Module variable? – Rojo Sep 19 '13 at 14:38
• You could pass x to f as a parameter. – Niki Estner Sep 19 '13 at 15:03
• 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. – Niki Estner Sep 19 '13 at 15:19
• 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 – Rojo Sep 19 '13 at 20:56
• @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... – sebhofer Sep 20 '13 at 19:23

Passing by reference:

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

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


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]