Unfortunately, I had not checked stackoverflow, because there, the exact same behavior was already reported. Please see the Q&A "SaveDefinitions considered dangerous".
Up-front, I'm on Ubuntu 12.04 with Mathematica 9.0.1 and let's start with the questions:
- Should functions which are used in a
Manipulate
be local to this dynamic cell, when Isave them with
SaveDefinitions`? - Is it OK, that after a kernel-restart
Manipulate
defines global functions?
I noticed this behavior a while ago when something did not work as I expected it. Here is a small toy example. First we define a function, which (we assume we don't know this now) is not correct and will be fixed later:
f[x_?NumericQ] := "Wrong Implementation";
Now we make a small dynamic environment where we use this function and we save the definitions used there.
Manipulate[f[x] + x, {x, 0, 1}, SaveDefinitions -> True]
Sliding a bit around gives the correct output:
Now, we notice our error in f
, because (let's say) f
is going to work even when we don't have numeric values. Therefore, we fix the pattern and evaluate
ClearAll[f]
f[x_] := "Correct Implementation!"
this redefinition is instantly shown in the Manipulate
, which is kind of weird, because we explicitly told Mathematica to save the definition and let me cite the documentation: SaveDefinition
...
is an option to Manipulate and related functions that specifies whether current definitions relevant for the evaluation of the expression being manipulated should automatically be saved.
There is even more, because when you now Quit[]
the kernel and then do nothing else that move the slider, you see that now the first definition is used again and the output changes to "Wrong Implementation"
. This seems fine, because Manipulate
finally remembers what is should have saved.
However, this is not what broke my neck. What really took time to debug was that the wrong definition of f
is leaked into the global context:
f[3]
(* "Wrong Implementation" *)
The problem back then, when I had this issue, was that although I evaluated the correct definition,
f[x_] := "Correct Implementation!"
the other one was used, because its pattern was more specific.
f[3]
(* "Wrong Implementation" *)
Any comments?
Comments
Post a Comment