我正在尝试用 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()
而不是列表返回。
任何建议或其他更多优雅的笛卡尔积解决方案将不胜感激。
最佳答案
您的问题出在这部分:
push @out_array, [$r . $c];
$r。 $c
将两个标量连接成一个字符串。 [EXPR]
创建一个数组引用。您不需要引用,只需要普通字符串:
push @out_array, $r . $c;
如果你不喜欢push,而是喜欢语法糖,你可以使用实现gather/take的模块:
my @cross = gather {
for my $x (@A) {
for my $y (@B) {
take $x . $y;
}
}
};
这是实现的,例如通过 List::Gather
或 Syntax::Keyword::Gather
.
我自己喜欢精心设计的 map
表达式:
my @cross = map { my $x = $_; map $x.$_, @B } @A;
(对于所有实际目的,与 for
和 push
相同)。
注意:Perl 没有与数组相关的“字符”概念。当需要单个字符时,这些字符由长度为 1 的字符串建模。Perl 数组总是包含标量,但出于(内存)性能原因,字符串不作为 Perl 数组实现,而是作为指向 C 数组(已知长度)的指针实现。缺点是字符串和数组的不同操作集,优点是内存使用量较少。
由于字符只是非常短的字符串,为了连接它们,我们使用带有 .
的标准字符串连接。
关于perl - 两个字符串的笛卡尔积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16948330/