|Think about Loose Coupling|
nested mapsby jczeus (Monk)
|on Apr 26, 2007 at 12:43 UTC||Need Help??|
Here is something interesting I found through playing around with map, my favorite Perl toy. I've not the faintest if this could be useful in a more general way or if it's just, well, interesting crap...
Here's how it emerged:
Just as an exercise, I wanted to generate a list of strings with a specific length from every possible combination of a list of characters.
But not with for loops, but with nested maps! In its simplest form, with 2 chars and strings with a length of two:
This produces aa, ab, ba, bb.
Adding characters is easy:
This produces aa, ab, ac, ba, bb, bc, ca, cb, cc.
But increasing the length of the string is not so easy. I did this by adding another nested map:
which, with qw( a b ), produces aaa, aab, aba, abb, baa, bab, bba, bbb. This is, of course, stupid.
One way to solve this problem is with a recursive function:
Now you could make it more general by adding a coderef parameter, string concatenation being only a special case needed in the original example:
So we have a function f that produces a list b by applying a function g to all possible combinations of a list a by calling itself recursively n times.
Is this useful? Or could it be further transformed so that it yields something useful?