Closed
Description
The problem
Benefits of using ModuleScope
and Scope
(instead of Module
and Block
):
- Not necessary to add new variables at the top of the block, i.e.
Module[{variables...}, ...]
(especially annoying in large functions). - Changing variable names is simpler (again because you don't have to rename the names at the top).
- Merging and splitting functions is easier as it is not necessary to merge and split their argument lists.
- No performance cost as these functions are (macro) expanded at definition time.
However, as @maxitg said:
... we still want to use
Module
in pattern rules (e.g.,{{a_, b_}} :> Module[{c}, {{a, c}, {c, b}}]
).ModuleScope
is undocumented so we cannot expose it to users.
Examples
You can use MacroExpand
to see what these functions do:
In[] := MacroExpand[foo[] := ModuleScope[
a = 1;
b = 2;
c = 3;
]]
In[] := MacroExpand[bar[] := Scope[
a = 1;
b = 2;
c = 3;
]]
Comment
It is not simply a matter of replacing all Module
's with ModuleScope
's. See:
In[] := MacroExpand[{x_, y_} :> ModuleScope[{x, y + 1, z}]]
You can use ScopeVariable
to "cause particular variables to be localized":
In[] := MacroExpand[{x_, y_} :> ModuleScope[ScopeVariable[z]; {x, y + z}]]
Activity