Created
April 24, 2013 01:48
-
-
Save mwgamera/5448977 to your computer and use it in GitHub Desktop.
Reshape multidimensional Perl array like with APL's dyadic ⍴ function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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