Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Iterative constants and variables definitions

54 views
Skip to first unread message

rych

unread,
Sep 20, 2006, 3:16:35 AM9/20/06
to
Thanks to everyone who commented on my previous topic "function's local
constants interdependence". I'd like to introduce 2 new functions, that
automate the nesting of several With[ and one Module[. I'd be thankful
for further suggestions.

(*Problem*)
In:=
With[{a=1,c=2,b=7a},a*b*c]
Out=
14 a
(*we wanted "14" *)

(*Solution*)

In[1483]:=
(*Hold'ed definitions*)
ClearAll[WithWith,WithModule]
SetAttributes[{WithWith,WithModule},HoldAll]

WithWith[x__,expr_]:=Fold[With[#2,#1]&,Hold[expr],
Reverse@Map[Hold,Unevaluated@{x}]/.Hold[h_[y__]]\[RuleDelayed]Hold[{h[y]}]/;h=!=
List]

WithModule[x__,expr_]:=With[{xh=Reverse@Map[Hold,Unevaluated@{x}]/.Hold[h_[y__]]\[RuleDelayed]Hold[{h[y]}]/;h=!=
List},With[{xh1=First@xh},Fold[With[#2,#1]&,Module[xh1,Hold[expr]],Rest@xh]]]

(*usage*)
Off[With::"lvlist"]
Off[Module::"lvlist"]
Clear[a,b,c]
b=100; c=200;

WithWith[{a=1, c=2},b=7a, a*b*c]
WithModule[{a=1, c=2},b=7a, a*b*c]


Out[1491]=
With[Hold[{a=1,c=2}],With[Hold[{b=7 a}],Hold[a b c]]]
Out[1492]=
With[Hold[{a=1,c=2}],Module[Hold[{b=7 a}],Hold[a b c]]]

(*final definitions*)
In[1494]:=
ClearAll[WithWith,WithModule]
SetAttributes[{WithWith,WithModule},HoldAll]
WithWith[x__,expr_]:=ReleaseHold@Fold[With[#2,#1]&,Hold[expr],Reverse@Map[Hold,Unevaluated@{x}]/.Hold[h_[y__]]\[RuleDelayed]Hold[{h[y]}]/;h=!=List]

WithModule[x__,expr_]:=With[{xh=Reverse@Map[Hold,Unevaluated@{x}]/.Hold[h_[y__]]\[RuleDelayed]Hold[{h[y]}]/;h=!=List},With[{xh1=First@xh},ReleaseHold@Fold[With[#2,#1]&,Module[xh1,Hold[expr]],Rest@xh]]]


(*usage*)
Off[With::"lvlist"]
Off[Module::"lvlist"]
Clear[a,b,c]
b=100;c=200;
WithWith[{a=1,c=2},b=7a,a*b*c]
WithModule[{a=1,c=2},b=7a,a*b*c]

Out[1502]=
14
Out[1503]=
14

dimm...@yahoo.com

unread,
Sep 21, 2006, 7:57:19 AM9/21/06
to

Ο/Η rych έγραψε:

dimm...@yahoo.com

unread,
Sep 21, 2006, 7:58:21 AM9/21/06
to
Very good your attempt.
I do not have anything to suggest/comment apart from
that you could do all these using Block.

Block[{a = 1, c = 2, b = 7*a}, a*b*c]
14

Module cannot be applied here

Module[{a = 1, c = 2, b = 7*a}, a*b*c]
14*a

Use Trace to see why

Trace[With[{a=1,c=2,b=7 a},a b c]]
{With[{a=1,c=2,b=7 a},a b c],(7 a) 2,2 (7 a),2 7 a,14 a}

Trace[Block[{a=1,c=2,b=7 a},a b c]]
{Block[{a=1,c=2,b=7 a},a b c],{a=1,1},{c=2,2},{b=7 a,7 a,{a,1},7 1,7},
{{a,1},{b,7 a,{a,1},7 1,7},{c,2},7 2,14},14}

Trace[Module[{a=1,c=2,b=7 a},a b c]]
{Module[{a=1,c=2,b=7 a},a b c],{a$17=1,1},{c$17=2,2},{b$17=7 a,7 a},
{{a$17,1},{b$17,7 a},{c$17,2},(7 a) 2,2 (7 a),2 7 a,14 a},14 a}

Regards
Dimitris

0 new messages