From af1ebf1ddb1ffed1f0f10aca8c31d79ba28f3421 Mon Sep 17 00:00:00 2001 From: Joelle Maslak Date: Mon, 17 Jun 2019 11:06:54 -0700 Subject: Solution for 13.2 in P5 & P6 --- challenge-013/joelle-maslak/perl5/ch-2.pl | 37 +++++++++++++++++++++++++++++++ challenge-013/joelle-maslak/perl6/ch-2.p6 | 21 ++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100755 challenge-013/joelle-maslak/perl5/ch-2.pl create mode 100755 challenge-013/joelle-maslak/perl6/ch-2.p6 diff --git a/challenge-013/joelle-maslak/perl5/ch-2.pl b/challenge-013/joelle-maslak/perl5/ch-2.pl new file mode 100755 index 0000000000..92e9ba379d --- /dev/null +++ b/challenge-013/joelle-maslak/perl5/ch-2.pl @@ -0,0 +1,37 @@ +#!/usr/bin/env perl + +use strict; +use warnings; + +use v5.22; + +# Turn on method signatures +use feature 'signatures'; +no warnings 'experimental::signatures'; + +# If you try computing say 1000 of these, you get a mess without +# caching. It gives deep recursion warnings and slowness. So we use +# Memoize to speed this up. +use Memoize; + +memoize('F'); +sub F($n) { + return 1 if $n == 0; + return $n - M( F($n-1) ); +} + +memoize('M'); +sub M($n) { + return 0 if $n == 0; + return $n - F( M($n-1) ); +} + +die("Must provide number of elements") if @ARGV != 1; +my $len = +$ARGV[0]; + +my @f = map { F($_) } (0..($len-1)); +my @m = map { M($_) } (0..($len-1)); + +say "F: " . join(" ", @f); +say "M: " . join(" ", @m); + diff --git a/challenge-013/joelle-maslak/perl6/ch-2.p6 b/challenge-013/joelle-maslak/perl6/ch-2.p6 new file mode 100755 index 0000000000..da9c25c506 --- /dev/null +++ b/challenge-013/joelle-maslak/perl6/ch-2.p6 @@ -0,0 +1,21 @@ +#!/usr/bin/env perl6 +use v6; + +use experimental :cached; + +sub MAIN(UInt:D $length) { + my @f = lazy (0..∞).map: { F($_) }; + my @m = lazy (0..∞).map: { M($_) }; + + say "F: { @f[^$length] }"; + say "M: { @m[^$length] }"; +} + +multi sub F(0) { 1 } +multi sub M(0) { 0 } + +# We cache these results, but can't use the cached trait (because it's a +# multi?), so we do it the old-fashioned way. +multi sub F($n where * > 0 ) { state %c; %c{$n} //= $n - M( F($n-1) ) } +multi sub M($n where * > 0 ) { state %c; %c{$n} //= $n - F( M($n-1) ) } + -- cgit