Skip to content

Instantly share code, notes, and snippets.

@mwgamera
Created April 24, 2013 01:48
Show Gist options
  • Save mwgamera/5448977 to your computer and use it in GitHub Desktop.
Save mwgamera/5448977 to your computer and use it in GitHub Desktop.
Reshape multidimensional Perl array like with APL's dyadic ⍴ function.
#!/usr/bin/env perl
use strict;
# reshape: A ⍴ B → rho [A], B
sub rho($@) {
my $s = 1;
my @shape = @{+shift};
'ravel' while $#_+1 < (@_ = map { ref eq 'ARRAY' ? @$_ : $_ } @_);
$s *= $_ for @shape;
@_ = @_[0 .. $s-1];
while ($#shape) {
$s = pop @shape;
@_ = map {[ @_[$_*$s .. $_*$s+$s-1] ]} 0 .. int($#_/$s);
}
return @_[0 .. $shape[0]-1];
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment