summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGuillermo Ramos2019-04-23 00:23:41 +0200
committerGuillermo Ramos2019-04-23 00:23:41 +0200
commit74b98d3b76ff216235cd6e2e649cec61ffde3ee0 (patch)
treeba34c42ba8e435e2a5de42adaec49308c7426f68
parent317ee36636ebeec986971ef857cd297f0320e58d (diff)
downloadeuler-74b98d3b76ff216235cd6e2e649cec61ffde3ee0.tar.gz
[perl] p1,p2
-rw-r--r--perl/p1.pl18
-rw-r--r--perl/p2.pl41
-rw-r--r--perl/template.pl9
3 files changed, 68 insertions, 0 deletions
diff --git a/perl/p1.pl b/perl/p1.pl
new file mode 100644
index 0000000..e13aa31
--- /dev/null
+++ b/perl/p1.pl
@@ -0,0 +1,18 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+use List::Util qw(reduce);
+
+# Functional
+print (reduce { $a + $b } (grep { $_ % 3 == 0 || $_ % 5 == 0 } 1..999));
+print "\n";
+
+# Imperative
+my $sum;
+foreach my $i (1..999) {
+ if ($i % 3 == 0 || $i % 5 == 0) {
+ $sum += $i;
+ }
+}
+print "$sum\n";
diff --git a/perl/p2.pl b/perl/p2.pl
new file mode 100644
index 0000000..ec85ec1
--- /dev/null
+++ b/perl/p2.pl
@@ -0,0 +1,41 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+
+# Functional (naïve)
+sub iter1 {
+ my ($fibs, $acc) = @_;
+ my ($a, $b) = @$fibs;
+ if ($a > 4_000_000) {
+ return $acc;
+ } else {
+ iter1([$b, $a+$b], $a & 1 ? $acc : $acc + $a);
+ }
+}
+print iter1([1, 2], 0);
+print "\n";
+
+# Functional (tail recursive)
+sub iter2 {
+ my ($fibs, $acc) = @_;
+ my ($a, $b) = @$fibs;
+ if ($a > 4_000_000) {
+ return $acc;
+ } else {
+ @_ = ([$b, $a+$b], $a & 1 ? $acc : $acc + $a);
+ goto &iter2;
+ }
+}
+print iter2([1, 2], 0);
+print "\n";
+
+# Imperative
+my ($a, $b) = (1, 2);
+my $resp = 0;
+do {
+ $resp += $a unless ($a & 1);
+ ($a, $b) = ($b, $a+$b);
+} while ($a <= 4_000_000);
+
+print "$resp\n"
diff --git a/perl/template.pl b/perl/template.pl
new file mode 100644
index 0000000..4f2ec78
--- /dev/null
+++ b/perl/template.pl
@@ -0,0 +1,9 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+
+# Functional
+
+# Imperative
+