... you know, when your mind is like, in a bottle?
Anyway, I was trying to do some permutations, and I wanted a recursive solution. I found a snippet of code that does it. However, I don't like putting code into my program without understanding what it does.
This code gives me memories of my lisp class in college:
#!/usr/bin/perl
print "permute:\n";
print "[", join(", ", @$_), "]\n" for permute([1,2,3], [4,5,6], [7,8,9
+]);
sub permute
{
my $last = pop @_;
unless(@_)
{
return map([$_], @$last);
}
return map {
my $left = $_;
map([@$left, $_], @$last)
}
permute(@_);
}
Here's what I can figure out so far.
The function goes into recursion until
@_ is empty, at which point it returns
[[1],[2],[3]] (or is it
([1],[2],[3])??) to the previous level of recursion.
At that level, I know that
$last is a reference to an array that contains
[4,5,6]. From there, it gets sort of confusing (inside the map). This is mainly due to my lack of experience with map. I know what it does in principle, but applying it recursively and with
$_, is giving me head-aches!
Any help is appreciated. Thanks!