In most languages, any variable defined inside a function is considered local.
# a Python function
def toRomanNumerals(num):
digits = # ...
string = ''
while num > 0:
(value, letters) = # ...
string = # ....
return string
In a Mathematica Module, however, we must specify a list of all variables to treat as local.
toRomanNumerals[i_Integer?Positive] :=
Module[{num = i, string = "", value, letters, digits},
digits = (* ... *);
While[num > 0, {value, letters} =
(* ... *);
string = (* ... *).];
string]
I sometimes find it tedious to manually type the list of all local variables. Do others feel the same way?
Is there a way to create a Module which treats all symbols defined inside as local?
Module[{}, f[x]]. Shouldfandxbe local or global? Perhaps you say thatfis global iffhas associated rules ("it's defined"), otherwise local, and the same applies tox. But what ifxhas a special meaning in the definition off, but it doesn't have any associated rules of its own? Say,f[big]=1; f[small]=0wheresmallandbigare symbols without definitions, but are used for a specific purpose. Even some builtins like$Predon't have a definition by default. – Szabolcs Nov 27 '13 at 20:25In most languages, any variablereally? What about Ada, Pascal, C, C++, Java, SNOBOL, PLI, COBOL? don't you have to declare variable? I much prefer Mathematica way. It is a form of documentation. One can look at the list of local variable and know which are local or which are not. Languages that do not require declaration are sloppy languages IMNSHO. ofcourse, in Mathematica, you do not have to declare local symbols as local, but this is bad, since they will become global. I think Mathematica got it right here. – Nasser Nov 27 '13 at 20:27In most languages, any variable declared inside a function is considered local.and I was replying to this. But any way. I myself do not languages that makes things implicit like this. I prefer explicit declarations. Much better in the long run. It helps build better software and better habit to learn to declare something before using it. – Nasser Nov 27 '13 at 20:44nonlocalkeyword, which allows one to tell the interpreter that we refer to a variable defined in a surrounding environment (I used it many times when I needed to define a closure in Python, although I am not sure that it is the most idiomatic way). In R, for example, there is a special<<-operator, which can be used to assign to the variable defined in outer scopes. – Leonid Shifrin Nov 27 '13 at 20:51