How do I return from an anonymous recursive sub in perl6?

  • A+
Category:Languages

This does what I'd expect. fib(13) returns 233.

sub fib(Int $a --> Int) {     return 0 if $a == 0;     return 1 if $a == 1;      return fib($a -1) + fib($a -2); }  my $square = -> $x { $x * 2 };   # this works with no return value my @list = <1 2 3 4 5 6 7 8 9>.map( $square ); # returns [2 4 6 8 10 12 14 16 18] 

I tried implementing fib() using an anonymous sub

my $fib = -> Int $x --> Int {     return 0 if $x == 0;     return 1 if $x == 1;     return $fib($x - 1) + $fib($x - 2);  }  $fib(13)  

I get the following error when running that with explicit returns.

Attempt to return outside of any Routine in block at test.p6 line 39

So I got rid of the return values.

my $fib = -> Int $x --> Int {     0 if $x == 0;     1 if $x == 1;     $fib($x - 1) + $fib($x - 2);  }  say $fib(13); 

This last version never returns. Is there a way to write an anonymous recursive function without return values?

 


According to the documentation :

Blocks that aren't of type Routine (which is a subclass of Block) are transparent to return.

sub f() { say <a b c>.map: { return 42 };                #   ^^^^^^   exits &f, not just the block  } 

The last statement is the implicit return value of the block

So you can try:

my $fib = -> Int $x --> Int {     if ( $x == 0 ) {         0;  # <-- Implicit return value     }     elsif ( $x == 1 ) {         1;  # <-- Implicit return value     }     else {         $fib($x - 1) + $fib($x - 2);  # <-- Implicit return value     } } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: