我想在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];'將包含一個字符串的數組引用推送到'@ out_array'。你不需要參考,所以跳過方括號。 'split' * always *返回字符串,永遠不會引用。 – amon
@amon謝謝,我對這一點感到困惑。 –