Home Website Changes Log in Log out

Perl6 Matrix Multiplication

We had some fun doing a matrix multiply in Perl6 (tested w/ Rakudo-Star 2010-08). We didn't use the most fancy of features, instead trying out some of the basic looping and so on. Though we did end up doing a zip-fold for some vector multiplication :)

my @m1 = (
  [ 1, 2, 3, 4],
  [ 5, 6, 7, 8],
  [ 9,10,11,12],
  [ 0, 0, 0, 1]);

my @m2 = (
  [1,0,0,0],
  [0,1,0,0],
  [0,0,1,0],
  [0,0,0,1]);

my $target_x = @m1[0].elems;
my $target_y = @m2.elems;

say "Target width: $target_x";
say "Target height: $target_y";

my @out;

loop (my $i = 0; $i < $target_x; $i++) {
  say "Working on row i = $i";
  loop (my $j = 0; $j < $target_y; $j++) {
    say "Working on col j = $j";
    my $row = @m1[$i];
    say "Got row: " ~ $row.perl;
    my @col = @m2.map: { $_[$j] };
    say "Got col: " ~ @col.perl;
    my $elm = [+] ($row Z* @col);
    say "Element: $elm";
    @out[$i][$j] = $elm;
  }
}

say "Result: " ~ @out.perl;
say "(and m1 is {@m1.perl})";