This evening a friend asked me if I knew how to easily flatten an array of arrays (AoA from now on) in Perl 5. What that means is, basically, to construct a single array that contains the concatenation of all the arrays inside the AoA.

My first answer was: "foldr", but I knew beforehand that he wouldn't like it because... this is Haskell. After some time we got to the conclusion that there is no trivial way to flatten an AoA in Perl 5, even though Perl 6 includes a built-in function to do so. He ended up using this code to resolve the problem:

my @ordered = map { @$_ } values %arches;

Ew, how ugly. Anyway, as part of the discussion, I then continued on my first answer just to show him how versatile functional programming is. And I said, hey, look at this nice example:

Hugs> foldr (++) [] [[1,2], [3,4]]

[1,2,3,4]


His answer: oh well, but it is easier in Ruby: just use the built-in ary.flatten function. Hmm... but why would I need a built-in function in Haskell when I can just redefine it in a trivial single line?

flatten = foldr (++) []

There you go, you can now flatten as much AoAs as you want! (Huh, no parameters? Well, you don't need to name them.) Isn't functional programming great? ;-)

PS: I know nothing about Ruby, but I bet you can write a very similar definition using this or other non-functional languages. I remember someone explaining somewhere (yeah, that's very specific) that Ruby has some patterns that resemble functional programming. So yes, you can probably define a flatten function by using something that looks like foldr, but that might look out of place in an imperative language. (Would be great to know about it for sure!)

Edit (June 9th): Added a link to my friend's blog.

Go to posts index

Comments from the original Blogger-hosted post: