3
$\begingroup$

Here is a minimal example:

    x = 4 + m;
    g = Sin[x];
    Module[{m = 1}, g]
    
   Sin[4 + m]  

So, why is m not replaced inside Module?

I know that I can solve this by setting g[m_] = Sin[x], but are there any alternatives to do that without redefining g?

$\endgroup$
0
6
$\begingroup$

Module does lexical scoping. That means that only the ms that are literally inside the module when it is evaluated are bound to the m of the module, other ms outside of the Module are unaffected (this is effectively done by replacing all occurrences of m in the body of the Module with a localized name like m$1234, which is then set to 1). In your case, the body of the Module is g, which does not contain m, so nothing happens.

As you have already noted, the best way would often be to pass in the value as a parameter. Another option is to use Block, which does dynamic scoping. This means that any m that is encountered while the body of the Block is evaluated is evaluated to 1 (this is effectively done by temporarily setting a global value to m):

x = 4 + m;
g = Sin[x];
Block[{m = 1}, g]
(* Sin[5] *)
$\endgroup$
1
  • $\begingroup$ thanks @Lukas Lang, exactly what I was looking for. Now, I see where I should use Block, With, and Module. Thanks again! $\endgroup$ Jul 29 at 13:27
3
$\begingroup$

This may be helpful:

x = 4 + m;
g = Sin[x];
Module[{m = 1}, Evaluate[g]]

The output is

Sin[5]
$\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.