News for hackers. Stuff that matters.
Re:Why it’s hard for programmers to write a program to flatt... by tzs on Friday February 24, 2017 @05:16PM (#13728446)
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.

There are no comments on this comment yet.