1
$\begingroup$

Often we use Module to construct complicate function. Consider that Module create new vars every time we run the function, should I remove the initial values at the end of Module-function?Or should I worry about it?

I never thought of this problem until I browse this question. the first comment under the question suggested 'Try ending the Module with result =plapla; Clear[...]; result'. However,when I test Module on my Mma9, it cleared the value of initial values automatically. That is to say, I have no way to recover the initial values of initial vars after I run the Module(If I didn't Print value out). for example,define:

f[x_] :=
Module[{a, b},
Print@ToString@a;
a = Range[1000]; a[[4]]
]

run f[2] it print the initial symbols a$$4120, however run a$4120 it returns a$4120 as if it had not been set value. So it's not necessary to explicitly Remove the initial symbols of Module at the end of Module?Right?

$\endgroup$
  • 1
    $\begingroup$ Right, those variables have Attribute Temporary which means you don't have to worry. $\endgroup$ – Kuba Jun 17 '15 at 16:01
  • $\begingroup$ It's only an issue when the local smbols get used in a way that leaks frfom Module (not your situation) or when DownValues are placed on them. $\endgroup$ – Daniel Lichtblau Jun 17 '15 at 18:07
  • 3
    $\begingroup$ @DanielLichtblau Actually, when I remember it right, DownValues by themselves are not a problem, as long as that symbol is not referenced from the outside. So, this is Ok: Module[{f}, f[1] = 1;f[1]], while this leads to a leak for f: Module[{g}, Module[{f}, g[x_] := f[x]; f[1] = 1;];g[1]], even though g has been later collected. I mentioned this case here. $\endgroup$ – Leonid Shifrin Jun 17 '15 at 21:01
  • $\begingroup$ @Leonid Shifrin Yes, good point. I thought there was some extra issue involved but did not recall what it was. $\endgroup$ – Daniel Lichtblau Jun 18 '15 at 11:09
  • $\begingroup$ Related: "Module trash collection behaviour." $\endgroup$ – Alexey Popkov Aug 23 '15 at 8:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.