aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xchallenge-122/e-choroba/perl/ch-1.pl67
-rwxr-xr-xchallenge-122/e-choroba/perl/ch-2.pl45
2 files changed, 112 insertions, 0 deletions
diff --git a/challenge-122/e-choroba/perl/ch-1.pl b/challenge-122/e-choroba/perl/ch-1.pl
new file mode 100755
index 0000000000..d7f574727d
--- /dev/null
+++ b/challenge-122/e-choroba/perl/ch-1.pl
@@ -0,0 +1,67 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+use feature qw{ say };
+
+# Stream is not an array. Stream is a source of values that can
+# produce new values infinitely.
+
+{ package Stream;
+ use Moo::Role;
+
+ requires qw{ first next_state };
+
+ has state => (is => 'rw', predicate => 1);
+ sub next_value {
+ my ($self) = @_;
+ $self->state($self->has_state
+ ? $self->next_state($self->state) : $self->first);
+ return $self->value
+ }
+ sub value { $_[0]->state }
+}
+
+{ package Stream::Sequence::Arithmetic;
+ use Moo::Role;
+ use MooX::Role::Parameterized;
+
+ with 'Stream';
+ role {
+ my ($params, $mop) = @_;
+ $mop->method(first => sub { $params->{first} });
+ $mop->method(next_state => sub { $_[1] + $params->{difference} });
+ };
+}
+
+{ package Stream::TenPlusTen;
+ use Moo;
+
+ 'Stream::Sequence::Arithmetic'->apply({first => 10,
+ difference => 10});
+}
+
+{ package Stream::Fibonacci;
+ use Moo;
+ with 'Stream';
+
+ sub first { [0, 1] }
+ sub next_state { [$_[1][1], $_[1][0] + $_[1][1]] }
+
+ around value => sub { $_[1]->state->[-1] }
+}
+
+sub stream_average {
+ my ($stream, $count) = @_;
+ my $sum = 0;
+ for my $tally (1 .. $count) {
+ my $n = $stream->next_value;
+ $sum += $n;
+ say $tally, "\t$n\t$sum / $tally\t", $sum / $tally;
+ }
+}
+
+say '10 + 10';
+stream_average('Stream::TenPlusTen'->new(), 10);
+
+say 'Fibonacci';
+stream_average('Stream::Fibonacci'->new(), 10);
diff --git a/challenge-122/e-choroba/perl/ch-2.pl b/challenge-122/e-choroba/perl/ch-2.pl
new file mode 100755
index 0000000000..96351f085e
--- /dev/null
+++ b/challenge-122/e-choroba/perl/ch-2.pl
@@ -0,0 +1,45 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+
+sub basketball_points {
+ my ($score) = @_;
+ return [] if 0 == $score;
+
+ my @result;
+ for my $shot (grep $_ <= $score, 1, 2, 3) {
+ push @result, map [$shot, @$_], basketball_points($score - $shot);
+ }
+ return @result
+}
+
+use Test2::V0;
+plan 2;
+
+is [basketball_points(4)], bag {
+ item [1, 1, 1, 1];
+ item [1, 1, 2];
+ item [1, 2, 1];
+ item [1, 3];
+ item [2, 1, 1];
+ item [2, 2];
+ item [3, 1];
+ end
+};
+
+is [basketball_points(5)], bag {
+ item [1, 1, 1, 1, 1];
+ item [1, 1, 1, 2];
+ item [1, 1, 2, 1];
+ item [1, 1, 3];
+ item [1, 2, 1, 1];
+ item [1, 2, 2];
+ item [1, 3, 1];
+ item [2, 1, 1, 1];
+ item [2, 1, 2];
+ item [2, 2, 1];
+ item [2, 3];
+ item [3, 1, 1];
+ item [3, 2];
+ end
+};