Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
4  
Don't put f as a Module variable? –  Rojo Sep 19 '13 at 14:38
2  
You could pass x to f as a parameter. –  nikie Sep 19 '13 at 15:03
1  
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. –  nikie Sep 19 '13 at 15:19
2  
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
1  
@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

2 Answers 2

up vote 7 down vote accepted

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

share|improve this answer

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]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.