Skip to content

Instantly share code, notes, and snippets.

@masak
Created March 29, 2011 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masak/892178 to your computer and use it in GitHub Desktop.
Save masak/892178 to your computer and use it in GitHub Desktop.
code for emulating multidimensional slices in Rakudo before we have the real thing
use v6;
use Test;
use Index::Multidim;
my @a =
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
;
is @a @@ '[1;1]', 5, 'multi-slice with two indices';
is @a @@ '[2;*]', [7, 8, 9], 'multi-slice with index and *';
is @a @@ '[*;0]', [1, 4, 7], 'multi-slice with * and index';
done;
use v6;
module Index::Multidim;
sub infix:<@@>($container, $description) is export {
$description ~~ / ^ '[' (\d+ | '*') ** ';' ']' $ /
or die "Unknown description '$description'";
my @path = map { ~$_ eq '*' ?? Whatever !! .Int }, $0.list;
return multi_slice($container, |@path);
}
sub multi_slice($container, *@path) {
my @current_locations = $container;
for @path -> $index {
if $index ~~ Whatever {
my @new_current_locations = gather for @current_locations -> $l {
for $l.keys -> $location {
take $l[$location];
}
};
@current_locations := @new_current_locations;
}
else {
@current_locations = (.[$index] for @current_locations);
}
}
return @current_locations;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment