Mathematica scoping / contexts / variable localization
- To: mathgroup at smc.vnet.net
- Subject: [mg105023] Mathematica scoping / contexts / variable localization
- From: Leo Alekseyev <dnquark at gmail.com>
- Date: Wed, 18 Nov 2009 06:58:36 -0500 (EST)
Dear Mathematica gurus,
One of the things that initially made Mathematica difficult for me to
use was scoping -- in particular, the fact that all symbols by default
appear in the global namespace. Even though this is a default
behavior for interactive evaluation in many packages, e.g.
R, in Mathematica, it leads to a greater potential for errors because
unlike those languages, in Mathematica
(1). a symbol can have multiple DownValues, and
(2). if one forgets to explicitly localize a symbol inside a scoping
construct, it may silently be taken from the global namespace.
After many years I finally figured out a (more or less) clean way to
structure my code and workflow, through a combination of defining
modules, contexts, packages, and careful use of Clear and Remove.
I still wonder, however, why there isn't a construct similar to Module
that would define a unique private context for _all_ symbols within
the construct (i.e. without having to declare them in a list). You
can kind of simulate this behavior by using BeginContext["MyCont`"]
together with redefining $ContextPath temporarily to only have
"MyCont`" and "System`". This is obviously too verbose to be of
practical use, but I do wonder why there isn't a built-in construct.
I suppose my question is -- is there a deep wisdom behind its absence,
or perhaps I am an anomaly in thinking that such behavior (automatic
lexical scoping for symbols in subroutines, present in R and
many others) would be incredibly handy?..
Prev by Date:
aliases and hot keys
Next by Date:
Re: Re: Re: Displaying results in a column
Previous by thread:
Re: aliases and hot keys
Next by thread:
Re: Mathematica scoping / contexts / variable localization