in reply to Syntactic sugar for tail call optimizations

I experimented with Sub::Call::Recur:
#!/usr/bin/perl use strict; use warnings; use Sub::Call::Recur qw(:all); use Memoize; memoize('sum'); sub sum { my ( $n, $sum ) = @_; if ( $n == 0 ) { return $sum; } else { recur ( $n - 1, $sum + 1); } } foreach my $sum ( \&sum ) { print $sum->(0, 0), "\n", $sum->(0, 1), "\n", $sum->(1, 0), "\n", $sum->(1, 1), "\n", $sum->(2, 2), "\n", $sum->(10, 1), "\n", $sum->(1000, 1), "\n"; }
It uses the Clojure - special_forms 'recur' to replace 'redo'.

Replies are listed 'Best First'.
Re^2: Syntactic sugar for tail call optimizations
by LanX (Saint) on May 27, 2011 at 15:24 UTC
    Thank you for pointing me to Sub::Call::Recur, very interesting!

    especially:

    It can be thought of as the redo operator, but for subroutines instead of loops.
    :)

    Actually I once read about recur in a Clojure book and wondered about the advantages to goto &sub

    Clearly - and as you demonstrated - there are two:

    1. One can use the "usual" call interface f(PARAS) instead of the cumbersome  @_=(PARAS);goto &f

    2. Memoize can't intercept and cache calls when goto-like constructions are used.

    OTOH Sub::Call::Recur relies on XS code... so I think I'd rather prefer to chose between the need of memoization for repeated runs or for speed and stack-sanity of one time runs.

    I think if I need both I could still realize my own memoization hash.

    Cheers Rolf