[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[FWP] Re: Neat or horrid?



Ariel Scolnicov wrote:
> Neat, but not as neat as primality testing...
> 
> Does it do proper tail recursion?  If not, I'd try
> 
>      sub sum {@_ ? shift () + goto &sum : 0}
> 
> except that it doesn't work (5.005_03).  I don't think I understand
> why not, though.

It's not tail-recursive --- the continuation for the call to &sum is
(in Scheme) (lambda (val) (+ (shift) val)), not (lambda (val) val),
which is what it would need to be for proper tail-recursion.

You could do something like

#!/usr/bin/perl -w
use strict;
sub sum { if ($#_) { unshift @_, shift() + shift; goto &sum } else { $_[0] }}
print sum (37), "\n";
print sum (48, 31, 11), "\n";

That's properly tail-recursive, but I don't think it's properly Fun.

-- 
<kragen@pobox.com>       Kragen Sitaker     <http://www.pobox.com/~kragen/>
The Internet stock bubble didn't burst on 1999-11-08.  Hurrah!
<URL:http://www.pobox.com/~kragen/bubble.html>
The power didn't go out on 2000-01-01 either.  :)


==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe