2 ms·
A similar trivial approach works in Perl: sub flatten { my @in = @{$_[0]}; my @out; while (@in) { my $item = shift @in;
by tzs 10y ago
A similar trivial approach works in Perl:
sub flatten
{
my @in = @{$_[0]};
my @out;
while (@in) {
my $item = shift @in;
if (ref $item eq 'ARRAY') {
unshift @in, @$item;
} else {
push @out, $item;
}
}
return \@out;
}
Input is a reference to the source list, output is a reference to the flattened list.
The main difference is that I opted to manipulate a copy of the source list in place to expand sublists rather than recurse.
As others have noted, a recursive version using map can be written much more concisely.