Re: Module/Block problem (passing pointers?)

• To: mathgroup at christensen.cybernetics.net
• Subject: [mg1852] Re: Module/Block problem (passing pointers?)
• From: wagner at bullwinkle.cs.Colorado.EDU (Dave Wagner)
• Date: Mon, 7 Aug 1995 20:27:16 -0400
• Organization: University of Colorado, Boulder

```In article <DCqqK6.DvM at wri.com>,
Scott Herod <sherod at boussinesq.Colorado.EDU> wrote:
>I've got a problem that seems to call for using the Block construct over
>a Module, but for other reasons, I Modules are more appropriate.  I'll
>show the set-up with a Block and ask how I can make it a module.  Here
>is the basic code.
>
>test1 := Block[{flag},
>  Print["1,1 ",flag];
>  test2;
>  Print["1,2 ",flag];
>]
>
>test2 := Module[{},
>  Print["2,1 ",flag];
>  flag = True;
>  Print["2,2 ", flag];
>]
>
>In[3]:= test1
>
>1,1 flag
>2,1 flag
>2,2 True
>1,2 True
>
>
>This does what I want, ie "flag" is a local variable to the test1's
>execution and test1 knows that the value of flag was set in test2.
>
>I would really like test1 to be defined in terms of a Module, not a Block.
>Any suggestions?
>
>Oh, in the real problem, test2 is already a function and it would be
>inelegant to have it return flag as well.
>
>If it were possible to pass pointers it would be easy to send test2 the
>flag pointer and then check it in test1.  But I believe that Mathematica
>can only pass values, correct?

You can pass symbols "by reference" by making giving the function
to which you are passing them one of the "Hold"-type attributes. E.g.,

In[8]:=
SetAttributes[settrue, HoldAll];
settrue[x_] := x = True

In[10]:=
Module[{flag},
Print[flag];
settrue[flag];
Print[flag];
]

flag\$10
True

Your choices are to hold either just the first argument (HoldFirst),
all but the first argument (HoldRest), or all of the arguments (HoldAll).

Alternatively, you could create the second function (your "test2")
without any attributes, and pass Unevaluated[flag] to the function.

In[11]:=
settrue2[x_] := x = True

In[12]:=
y = False;
settrue2[Unevaluated[y]]
Out[13]=
True

In[14]:=
y
Out[14]=
True

Just be sure not to accidentally leave out the Unevaluated:

In[15]:=
y = False;
settrue2[y]

Set::wrsym: Symbol False is Protected.

Out[16]=
True

Dave Wagner
Principia Consulting
(303) 786-8371
dbwagner at princon.com
http://www.princon.com/princon

```

• Prev by Date: Re: Module/Block problem (passing pointers?)
• Next by Date: Re: RealDigits
• Previous by thread: Re: Module/Block problem (passing pointers?)
• Next by thread: Module/Block problem (passing pointers?)