Saturday, October 31, 2009

Sub::Call::Tail

I've just released Sub::Call::Tail which allows for a much more natural tail call syntax than Perl's goto built in.

It provides a tail keyword that modifies normal invocations to behave like goto &sub, without needing the ugly @_ manipulation.

Instead of this horrible kludge:

@_ = ( $foo, $bar );
goto &foo;

You can now write:

tail foo($foo, $bar);

And much more importantly this method call emulation atrocity:

@_ = ( $object, $foo, $bar );
goto $object->can("foo");

Can now be written as:

tail $object->foo($foo, $bar);

Finally we can write infinitely tail recursive and CPS code with a constant stack space, without the syntactic letdown that is goto. Lambdacamels rejoice!

Thanks so much to Zefram for his numerous tests and contributions.

7 comments:

Paul Driver said...

*rejoices*

oylenshpeegul said...

*also rejoices*

Note that it didn't install until I first installed B::Hooks::OP::Check::EntersubForCV.

Shlomi Fish said...

Looks very cool. However, I'm not sure it is of immediate use to me.

nothingmuch said...

The uses are for writing functional programming style algorithms, for example using recursion instead of loops, without allocating O(N) stack

melo said...

The timing and topic of your post is interesting. Did you read this article, Tail Call Amputation?

Nice stuff.

nothingmuch said...

@melo: no, I did not. That's pretty cute, and should be very easily to implement in perl (pretty much just recreate @_, and unwind the context stack to the last sub, and set PL_op = CvSTART)

Using B::Hooks::XSUB::CallAsOp it should be pretty easy to implement this without losing too much sanity.

nothingmuch said...

@melo: uploaded Sub::Call::Recur