Raku / old-design-docs

Raku language design documents
https://design.raku.org/
Artistic License 2.0
124 stars 36 forks source link

"recurse" keyword instead of &?ROUTINE #37

Closed grondilu closed 11 years ago

grondilu commented 11 years ago

found the idea here: http://rosettacode.org/wiki/Anonymous_recursion#PicoLisp

lizmat commented 11 years ago

Could you elaborate on how this would look in a code example? Before and after?

moritz commented 11 years ago

Note that &?ROUTINEis much more general than recurse. You can not only call it, but pass it around, introspect it, mix in roles etc.

So I don't think adding recurse is worth it. How often do you actually recurse into anonymous functions in real-world code? And if you recurse into named functions, using the name is preferable to using &?ROUTINE, because then refactoring is less likely to lead to recursion into the wrong routine.

moritz commented 11 years ago

Oh, one more thing: you can actually implement recurse as a subroutine yourself. This code works in rakudo:

sub recurse(|args) {
    my $level = 2;
    loop {
        my $cf = callframe($level);
        die "Called &recurse outside the scope of a function" unless defined $cf;
        my $routine = $cf.my<&?ROUTINE>;
        if $routine ~~ Routine {
            return $routine(|args);
        }
        $level++;
    }
    Nil;
}

my $fib = sub ($x) {
    $x > 1 ?? $x * recurse($x-1) !! 1;
}
say $fib(5);

So if you want it badly, you can always write a module that supplies it.