Last active
March 22, 2019 09:47
-
-
Save xtetsuji/ee59c474734dc0921a197012c370bd5c to your computer and use it in GitHub Desktop.
samples for getting Fibonacci function from closure function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
sub get_fib_with_initvals { | |
my ($first, $second) = @_; | |
# Perl の代入は右結合なので、 my $fib = sub { ... } で右辺に $fib があってはいけない。 | |
# この場合、宣言と代入を分けて書く必要がある | |
my $fib; | |
$fib = sub { | |
my $n = shift; | |
die "argument is required as digit" if !is_digit($n); | |
if ( $n == 0 ) { | |
return 0; | |
} elsif ( $n == 1 ) { | |
return $first; | |
} elsif ( $n == 2 ) { | |
return $second; | |
} else { | |
return $fib->($n-1) + $fib->($n-2); # 再帰呼び出し | |
} | |
}; | |
return $fib; | |
} | |
sub is_digit { | |
my $arg = shift; | |
if ( defined $arg && $arg =~ /^\d+$/ ) { | |
return 1; | |
} else { | |
return; | |
} | |
} | |
my $fib = get_fib_with_initvals(7, 11); | |
for my $i (1..10) { | |
printf "%d: %d\n", $i, $fib->($i); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
def get_fib_with_initvals(first, second) | |
# Ruby の代入は単純な右結合ではない | |
fib = lambda do |n| | |
raise "argument is required as digit" if !n.kind_of?(Integer) | |
if n == 0 | |
return 0 | |
elsif n == 1 | |
return first | |
elsif n == 2 | |
return second | |
else | |
return fib.call(n-1) + fib.call(n-2) | |
end | |
end | |
fib | |
end | |
fib = get_fib_with_initvals(7, 11) | |
(1..10).each do |i| | |
printf "%d: %d\n", i, fib.call(i) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1: 7 | |
2: 11 | |
3: 18 | |
4: 29 | |
5: 47 | |
6: 76 | |
7: 123 | |
8: 199 | |
9: 322 | |
10: 521 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment