Re: Workaround for an unexpected behavior of Sum

```Hi,

> Yes Andrzej, I agree, you are right, I can see know very important
>
> ONE: Using the flag, you avoid an infinite loop (actually, infinite
> recursion). The equivalent action in my approach was to verify if
> Unevaluated[dummyindex] is the same as the evaluated dummyindex. In my case,
> the evaluation of dummyindex could take a long time. We actually cannot know
> in advance how much time would that evaluation take, it depends whatever the
> end user has stored in dummyindex, which could be a long program that takes
> a lot of time to evaluate. Even worst, the evaluation of dummyindex could
> have unwanted results or side effects, again it depends on the content of
> dummyindex. Therefore my approach is potentially inefficient and potentially
> dangerous. On the other hand, in your approach you only verify if the flag
> is True or False: always fast, always safe, always reliable, great!

I'm not in a position to criticize Adrzejs approach, but the following
solution seems to achieve the same in a different way and has some
advantages in my opinion, so it might also be of interest.

By using ValueQ (or accessing OwnValues directly) you can easily decide
whether or not a Symbol has a value without evaluating. So something
like this would also do the job:

Unprotect[Sum];
Sum[
sumand_,
before___,
{dummyindex_Symbol /; ValueQ[dummyindex], rest___},
after___
] := Module[{dummyindex},
Sum[sumand, before, {dummyindex, rest}, after]
];
Protect[Sum];

I'm sure this approach has it's limits too (there could be additional
trouble with UpValues or DownValues of the index), but I like it for the
following reasons:

1) no dependence on the state of a global variable, which for whatever
reason could be left in an inappropriate state (see e.g. nested sums below).
2) it is minimal invasive: it only intervenes when obviously necessary
3) it works also with nested sums:

j=1;k=2;
Sum[Sum[f[j], {j, 1, k}], {k, 1, n}]

j = 1; k = 2;
Sum[f[j, k], {k, 1, n}, {j, 1, k}]

>> This confirms that the behavior of Sum is a bug.
>>
>> Andrzej Kozlowski

After all a reliable solution can only be achieved by Wolfram in this
case, everything else is just a workaround...

hth,

albert

```

• Prev by Date: More Inquiries
• Next by Date: Re: Re: No preferences for OSX
• Previous by thread: Re: RE: Re: Workaround for an unexpected behavior of Sum
• Next by thread: RE: Re: Workaround for an unexpected behavior of Sum