develooper Front page | perl.perl6.language | Postings from June 2005

Re: return() in pointy blocks

Thread Previous | Thread Next
From:
Piers Cawley
Date:
June 8, 2005 07:07
Subject:
Re: return() in pointy blocks
Message ID:
m2br6hkkmz.fsf@obelisk.bofh.org.uk
Piers Cawley <pdcawley@bofh.org.uk> writes:

> "TSa (Thomas SandlaƟ)" <Thomas.Sandlass@orthogon.com> writes:
>
>> Piers Cawley wrote:
>>> My preference is for:
>>>     Boo
>>>     Boo
>>>     Can't dereferene literal numeric literal 42 as a coderef.
>>
>> How do you reach the second 'Boo'? Iff -> does not create a Sub
>> but a Block instance then Luke's code can be interpreted as a
>> much smarter version of
>
> I really wish you'd quote in more detail, it makes it a real PITA to go back
> and find the explanatory code.  
>
>     sub foo () {
>       return -> { return 42 }
>     }
>
>     my $code =   foo();
>     #          ^--- continuations points to the RHS of the assignment
>     say "Boo!";
>     $code();
>
> So, this is what happens.
>
> 1. foo() returns a coderef to the RHS of the assignment.
> 2. The coderef gets assigned to $code.
> 3. say "Boo!"
> 4. We invoke the coderef, which returns 14 to continuation which was current
>    when it was created.
> 5. That means 42 gets returned to the RHS of the assignment
> 6. say "Boo!"
> 7. Try to invoke the literal 42. 
> 8. Die.
>
> In other words, it outputs:
>
>    Foo
>    Foo
>    # dies


If that works, then I think it means we can write:

    sub call-with-current-continuation(Code $code) {
        my $cc = -> $retval { return $retval }
        $code($cc);
    }

Which I personally think is rather cute. Even if I can't quite bring myself to
believe it's that simple... 

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About