This is my fourth week participating into the weekly challenge.
Easy Challenge
“Write a program that demonstrates using hash slices and/or array slices.”
This one isn’t too difficult, populate and array and hash and show a splice of each. Inf is quite useful in Raku but don’t map it into a hash 🙂
Perl 5 solution
#!/usr/bin/perl
# Test: ./ch1.pl
use strict;
use warnings;
use feature qw /say/;
my @array = (0,1,2,3,4,5,6,7,8,9);
my %hash = (a => 1, b => 2, c => 3, d => 4);
say 'Array slice: ' . join ' ', @array[0..5];
say 'Hash slice: ' . join ' ', @hash{'a','b'};
Output
Array slice: 0 1 2 3 4 5
Hash slice: 1 2
Raku solution
# Test: perl6 ch1.p6
use v6.d;
sub MAIN () {
my @array = (0..Inf);
my %hash = ( a => 1, b => 2, c => 3, d => 4 );
say 'Array slice: ' ~ @array[0..5];
say 'Hash slice: ' ~ %hash{'a','b'};
}
Output
Array slice: 0 1 2 3 4 5
Hash slice: 1 2
Hard Challenge
“Write a program that demonstrates a dispatch table.”
I created a dispatch_table using a hash and imaginatively called it ‘dispatch_table’. I also decided to show the dispatch table with an anonymous function.
In my Raku solution, I learned quite a few things like having to Coerce a match object so that it would work with the referenced function.expected Num but got Match (Match.new(hash => Map.new(…)
I also had to do some research on how Raku does regexs, I got a bit lazy and probably should have put the regex into a variable (and does it allow capturing?)
Perl 5 solution
#!/usr/bin/perl
# Test: ./ch2.pl
use strict;
use warnings;
use feature qw(say);
my %dispatch_table = (
'+' => \&add,
'-' => \&subtract,
'x' => sub { return ($_[0] * $_[1]); },
'/' => sub { return ($_[0] / $_[1]); },
);
my @equations = ('2 + 2', '10 - 4', '3 x 3', '25 / 5');
for my $equation (@equations) {
next unless ($equation =~ /^(\d+)\s*([\+\-x\/])\s*(\d+)$/);
# $1 = left, $2 = operator, $3 = right
say $equation . ' = ' .
$dispatch_table{$2}->($1, $3);
}
sub add { return ($_[0] + $_[1]); }
sub subtract { return ($_[0] - $_[1]); }
Output
2 + 2 = 4
10 - 4 = 6
3 x 3 = 9
25 / 5 = 5
Raku solution
# Test: perl6 ch2.p6
use v6.d;
sub MAIN () {
my %dispatch_table = (
'+' => &add,
'-' => &subtract,
'x' => sub ($a , $b) { $a * $b },
'/' => -> $a , $b { $a / $b },
);
my @equations = ('2 + 2', '10 - 4', '3 x 3', '25 / 5');
for (@equations) -> $equation {
($equation ~~ /^(\d+)\s*(\+|\-|x|\/)\s*(\d+)$/);
say $equation ~ ' = ' ~
%dispatch_table{$1}($0, $2);
}
}
sub add(Num() $a, Num() $b) { return ($a + $b); }
sub subtract(Num() $a, Num() $b) { return ($a - $b); }
Output
2 + 2 = 4
10 - 4 = 6
3 x 3 = 9
25 / 5 = 5
One thought on “PERL WEEKLY CHALLENGE – 034”