David Storrs writes:
> Given this code:
>      
>     if ( some_expensive_lookup_function() >= $MAX_RECORDS ) {
>        mark_that_we_have_reached_max_records();       
>        return;
>     } 
> 
> After I enter that block once, I never want to evaluate the condition
> again--I want the code to completely disappear from the bytecode (or,
> at least, be jumped around).  How would I do that in Perl 6?

Hmm...

    my $max_reached;
    sub mark_that_we_have_reached_max_records() {
        $max_reached = 1;
    }

    if !$max_reached && some_expensive_lookup_function() > $MAX_RECORDS {
        mark_that_we_have_reached_max_records();
        return;
    }

That's a new feature we're adding called "conditional code removal",
sometimes known as "short circuiting" :-)

I've given some thought to this sort of thing for optimization, however.
Obviously a conditional on a variable isn't a big price to pay, but when
you have a lot of them, removing the code altogether might save you some
important cycles.  This is particularly true if this condition is within
a tight loop.

So, let's say you have something like:

    $x = 100_000;
    my $seen;
    while $x --> 0 {
        if $seen || cheap_condition() {
            something();
        }
        $seen++ if other_cheap_condition();
    }

We'd like this to be easy to unroll into:

    $x = 100_000;
    while $x --> 0 {
        if cheap_condition() {
            something();
        }
        last if other_cheap_condition();
    }
    while $x --> 0 {
        something();
    }

Especially if something() is a complex expression that's prone to typing
errors, we'd like to keep out the code duplication.

This could well be something the optimizer does, but assuming otherwise,
optimized currying could be to our benefit.

    sub do_the_loop($x, $seen) {
        while $x --> 0 {
            if $seen || cheap_condition() {
                something();
            }
            last if !$seen && other_cheap_condition();
        }
        return $x;
    }

    &do_the_loop.assuming(seen => 1).(
        &do_the_loop.assuming(seen => 0).(100_000));

If curries are subject to a short constant-folding pass, this should
easily give us the effect we want.

> (I recall seeing something about how to make assertions drop out, but
> I want to be able to do this at run-time, not compile-time.)

As uri said, who can tell the difference?

Luke

Reply via email to