Re: Visibility of value of variable bindings in module
- To: mathgroup at smc.vnet.net
- Subject: [mg121239] Re: Visibility of value of variable bindings in module
- From: Leonid Shifrin <lshifr at gmail.com>
- Date: Tue, 6 Sep 2011 03:54:51 -0400 (EDT)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- References: <201109042205.SAA21480@smc.vnet.net>
Hi Chris,
As others noted, there is no built-in form that would do that. There were
however
several attempts to define such an operator within Mathematica. Here is
mine:
ClearAll[LetL];
SetAttributes[LetL, HoldAll];
LetL /: Verbatim[SetDelayed][lhs_, rhs : HoldPattern[LetL[{__}, _]]] :=
Block[{With}, Attributes[With] = {HoldAll};
lhs := Evaluate[rhs]];
LetL[{}, expr_] := expr;
LetL[{head_}, expr_] := With[{head}, expr];
LetL[{head_, tail__}, expr_] :=
Block[{With}, Attributes[With] = {HoldAll};
With[{head}, Evaluate[LetL[{tail}, expr]]]];
What it does is to macro-expand the definition into nested `With` at
definition-time. Here is a simple example:
In[29]:= LetL[{a=2,b=a+3,c=a+b+4},c]
Out[29]= 11
Because the definition is expanded not at run-time but at definition-time,
LetL preserves the semantics of functions defined with patterns having local
variables shared between the body and the condition. In particular, this
will work:
Clear[f];
f[x_,y_]:=LetL[{xl=x,yl=y+xl+1},xl^2+yl^2/;(xl+yl<15)];
f[x_,y_]:=x+y;
?f
Global`f
f[x_,y_]:=With[{xl=x},With[{yl=y+xl+1},xl^2+yl^2/;xl+yl<15]]
f[x_,y_]:=x+y
By nature of the LetL function (macro), it should play well with other
(built-in)
scoping constructs for issues like variable name conflicts in nested scoping
constructs.
There won't alas be code highlighting for it.
The more extended discussion of this construct lives here:
http://stackoverflow.com/questions/5866016/question-on-condition/5869885#5869885
,
where I also provided a link to the original Mathgroup thread where this
code
was first published.
I did not do it, but one should be able to write a similar macro for Module.
Hope this helps.
Regards,
Leonid
On Mon, Sep 5, 2011 at 2:05 AM, caw <cawright.99 at gmail.com> wrote:
> Hi
>
> Module[{x = Sum[i, {i, Length[{1, 2, 3}]}], y = x + 1}, Print[y];
> Print[x]]
>
> prints out:
>
> 1 + x
> 6
>
> So, in the variable declaration section of the Module statement, the
> binding of x to 6 isn't visible to y.
> (It's a bit like let and let*, but not)
>
> Is there a form which will allow the bindings to be visible within the
> variable declaration section?
>
> thanks very much
>
> chris
>
>
- References:
- Visibility of value of variable bindings in module
- From: caw <cawright.99@gmail.com>
- Visibility of value of variable bindings in module