As indicated in a recent post, the scope within the module does not work.
An example from this thread:
Module[{expr}, expr = 2 z; f[z_] = expr; f[7]] (*2 z*)
But the following works almost as expected.
Module[{expr}, expr = 2 z; Set@@{f[z_], expr}; f[7]] (*14*)
What language design made tungsten choose this functionality?
Edit: see Jefromi's first comment. I changed z to a local variable and did not forget to change the output. This does not affect the problem.
Edit2: It seems that Michael Pilate's position is that the block and module have different functions. I think I understand his point of view, but I think that is orthogonal to my question. So here is the update.
I can use the following code globally in a laptop:
expr = 2 z; f[z_] = expr; f[7] (*output: 14*)
But when I put the same block of code in the module and do expr local, it produces a different output.
Clear[f]; Module[{expr}, expr = 2 z; f[z_] = expr; f[7]] (*output: 2z*)
If you follow the above module call, you will find that Set [f [z_], expr] is rewritten to Set [f [z $ _, expr]. Now this transformation z-> z $ occurs on both lhs and rhs Set. However, this happens before expr is evaluated, which leads to another result being obtained globally.
The z-> z $ conversion seems to happen only when rhs has a character local to the module call.
Why did Mathematica decide to change this syntax in a module call? What trade-offs between language and project implementation exist here that made this decision.
programming-languages wolfram-mathematica
Davorak
source share