2
$\begingroup$

I'm running Mathematica 12.2 and have encountered the following unexpected behavior with Manipulate:

Block[{G},       
     G[x_]:=x;
     DynamicModule[{x}, 
        Manipulate[
            G[x],
            {{x, -1, "x"}, -1, 1, Appearance->"Labeled"}
     ]]]

I anticipate Manipulate will recognize the definition of G and so will show the value of x. It does not. G is unevaluated. Without the surrounding Manipulate, G is evaluated. Without the surrounding Block, G is evaluated. Without the DynamicModule, G is evaluated. Bug? Am I missing something?

$\endgroup$
3
  • 3
    $\begingroup$ When the Block evaluates it returns a DynamicModule, and at that point all definitions you have given to G are gone. Why not use something like DynamicModule[{G, x}, G[x_] := .....]? $\endgroup$
    – Jason B.
    May 20 at 16:57
  • 1
    $\begingroup$ If I use the menu command Help > Why the coloring?... then I get a dialog that there is an "order of evaluation conflict" with G. Not a complete explanation, but it is what @JasonB. is pointing out. $\endgroup$
    – Michael E2
    May 20 at 17:26
  • 1
    $\begingroup$ Related/duplicate: mathematica.stackexchange.com/questions/55121/… -- And this: groups.google.com/g/comp.soft-sys.math.mathematica/c/… $\endgroup$
    – Michael E2
    May 20 at 17:36
3
$\begingroup$

Use InputForm to examine the output of your code, not just how it formats:

(*In*)
InputForm @ Block[{G},
    G[x_] := x;
    DynamicModule[{x}, Manipulate[G @ x, {{x, -1}, -1, 1}]]
]

(*Out*)
DynamicModule[{x}, Manipulate[G[x], {{x, -1}, -1, 1}], DynamicModuleValues :> {}]

You see that the Block evaluated and returned a DynamicModule, as should be expected. The definition of G has evaporated along with the Block. Look at what we get switch the Block to Module:

DynamicModule[{x}, Manipulate[G$4159[x], {{x, -1}, -1, 1}], DynamicModuleValues :> {}]

Here the scoped variable escaped the Module and keeps its definition, so this now works.

I think the best route to go is to localize G in the DynamicModule:

In[2]:= InputForm @ DynamicModule[{G}, G[x_] := x; Manipulate[G@x, {{x, -1}, -1, 1}]]

Out[2]//InputForm=
DynamicModule[{G}, Manipulate[G[x], {{x, -1}, -1, 1}], 
 DynamicModuleValues :> {{DownValues[G] = {HoldPattern[G[x_]] :> x}}}]
$\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.