       Re: Is this a bug?

• To: mathgroup at smc.vnet.net
• Subject: [mg32096] Re: Is this a bug?
• From: "Allan Hayes" <hay at haystack.demon.co.uk>
• Date: Sun, 23 Dec 2001 03:52:35 -0500 (EST)
• References: <9vs8ph\$g1d\$1@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```Paul,

1

Here is a version of Increment that seems to be close to the built in one,
(follow the latter's evaluation with TracePrint, there is no evidence of the
use of With in the built in function  but the main evaluation steps are the
same).

Attributes[incr]={HoldFirst};  (*Increment is HoldFirst*)
incr[x_]:= With[{t=x},x=t+1;t]

Compare

k[x_]:=Module[{},Print["hallo world"];x];

a=a5;
incr[a[k]]

hallo world
hallo world

a5

Explanation:
Because of incr being HoldFirst the main steps in the evaluation of
incr[a[k]] are as follows

With[{t=a[k]},a[k]=t+1;t]
With[{t=a},a[k]=t+1;t] (*+ first print *)
With[{t=a5},a[k]=t+1;t]
a[k]=a5+1;a5 (*+ second print *)
a = a5+1;

2

Let's modify Random so that we get a printout of what the selections are

ri:=(Print[#];#)&[ Random[Integer]]

a:=a0;a:=a1;
Do[ a[ri]++;Print[{a,a}], {3} ];

0
0
{1 + a0, a1}
0
1
{1 + a0, 2 + a0}
1
0
{3 + a0, 2 + a0}

Following the code in 1 above successive evaluations of the body of Do[..]
give the assignments
a = a+1 = a0+1
a = a+1 = (a0+1) +1 = a0+2
a = a+1 = (a0+2)+1 = a0

The general situation is that an evaluation of the body that begins by
giving the printouts
i
j
will make the assignment
a[j] = a[i]

Here is another example

a:=a0;a:=a1;
Do[ a[ri]++;Print[{a,a}], {3} ];

0
1
{a0, 1 + a0}
0
1
{a0, 1 + a0}
0
1
{a0, 1 + a0}

--
Allan

---------------------
Allan Hayes
Mathematica Training and Consulting
Leicester UK
www.haystack.demon.co.uk
hay at haystack.demon.co.uk
Voice: +44 (0)116 271 4198
Fax: +44 (0)870 164 0565

"Paul van Wamelen" <wamelen at math.lsu.edu> wrote in message
news:9vs8ph\$g1d\$1 at smc.vnet.net...
> Is the following a bug?
>
> Mathematica 4.1 for Sun Solaris
> Copyright 1988-2000 Wolfram Research, Inc.
>  -- Motif graphics initialized --
>
> In:= k[x_] := Module[{},Print["hallo world"];x];
>
> In:= a = 0;
>
> In:= a[k]++
> hallo world
> hallo world
>
> Out= 0
>
>
> I would have expected only one "hallo world" and it would seem to be
> more efficient to only evaluate the k once...
>
> The above example is not important but in the form below it had me
> baffled for a while:
>
> In:= tst[n_] := Module[{a},
>   a = a = 0;
>   Do[a[Random[Integer,{0,1}]]++,{n}];
>   {a,a}]
>
> In:= tst
>
> Out= {24, 24}
>
> (Does not add up to 50!)
>
> Thanks!
>
>
>

```

• Prev by Date: Re: Displaying Mathematica's Global rules
• Next by Date: Find many Roots
• Previous by thread: Re: Re: Is this a bug?
• Next by thread: Re: Re: Is this a bug?