in reply to Re: for loop localisation bug?
in thread for loop localisation bug?

Turing goes a step further and explicitly forbids the use of an iterator variable outside of the loop its used in. In that language you dont have to declare an iterator, and it disappears as soon as the loop terminates.

And I believe the reason for this logic is that the value can be undefined depending on how the compiler handles it. Ie:

for my $i (0..10) { print "$i\n" }

Could be optimised into ten print statements with no iterator at all.


---
demerphq

    First they ignore you, then they laugh at you, then they fight you, then you win.
    -- Gandhi


Replies are listed 'Best First'.
Re: Re: Re: for loop localisation bug?
by BrowserUk (Patriarch) on Dec 29, 2003 at 19:12 UTC

    Ah! But what about

    my $i; for $i ( 0 .. 10 ) { last if $i == 5; } print $i;

    This could equally be optimised to remove the loop, but optimising the iterator away would be an error. In this case, the modification of the iterator is the primary purpose of the loop.

    Of course, this is grossly simplified, the break condition would not be a comparison against a constant, and in the original scenario, the iterator was being used as the index into an array. In other words, the loop was searching an array for a particular value and the desired outcome is the index of the array at which it is found.

    This isn't exactly an unusual use of a for loop

    How would this be done in Turing?


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    Hooray!

      Well, depending on the rest of the code, and the sophistication of the compiler one could postulate reasonably that it might be optimised to

      print 5;

      As for Turing you would say (and I forget most of my turing so ill write in Perl as if it were Turing)

      my $value; for $i (0..10) { if ($i==5) { $value=$i; last; } } print $value;

      Actually thats much the same as what you need to do in Perl anyway (if you are interested in the value of the iterator afterwards.) IMo, its arguable that you would be better served by a while loop anyway, at least thats what I usually do in this type of scenario.

      Oh, Happy New Year mate. :-)


      ---
      demerphq

        First they ignore you, then they laugh at you, then they fight you, then you win.
        -- Gandhi