我正在尝试在Perl中编写一个函数来计算两个字符串的叉积(笛卡尔积)。我在Python中有类似的代码,如下所示:
def cross(A, B):
"Cross product of elements in A and elements in B."
return [a+b for a in A for b in B]
我该如何优雅地模仿这个列表推导式?
以下是我目前的代码:
# compute the cross product of two Strings
# cross('12','AB') = ((1,A), (1,B), (2,A), (2,B))
sub cross {
# unpack strings
my ($A, $B) = @_;
# array to hold products
my @out_array;
# split strings into arrays
my @A_array = split(//, $A);
my @B_array = split(//, $B);
# glue the characters together and append to output array
for my $r (@A_array) {
for my $c (@B_array) {
push @out_array, [$r . $c];
}
}
return \@out_array;
}
这并不完全按照我的预期工作,某些原因导致split()
返回的是引用而不是列表。
如果有任何建议或者更加优雅的笛卡尔积解决方案,将不胜感激。
$r . $c
组成的字符串推入@out_array
数组中作为一个数组引用。如果你不需要这个引用,可以跳过方括号。函数split
永远返回字符串,而非引用。 - amon