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

Re: [FWP] Re: Neat or horrid?



On Sun, May 28, 2000 at 09:51:57AM +0300, Ariel Scolnicov wrote:
> abigail@arenanetworks.com writes:
> 
> > Here's a interesting way to sum the elements of a list:
> > 
> >     sub sum {@_ ? shift () + &sum : 0}
> > 
> > 
> > Neat or horrid?
> 
> 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.

C<goto &sum> _replaces_ the current subroutine call with a call to the
specified subroutine.  That's quite different from C<&sum>, which calls the
specified subroutine and returns its result to the current subroutine
call.  C<goto &sum> doesn't return; it can't, because its calling context
has been replaced.

#!perl

sub no_goto {
  print "no_goto\n";
  &go;
  print "no_goto\n";
}

sub with_goto {
  print "with_goto\n";
  goto &go;
  print "with_goto\n";
}

sub go {
  print "  go\n";
}


no_goto();
print "\n";
with_goto();

__END__

no_goto
  go
no_goto

with_goto
  go


Ronald

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