我有一个列表列表(在erlang中,字符串是列表),如下所示:
[“abc”,“def”]
我希望在函数返回的列表中获得以下组合:
[“ad”,“ae”,“af”,“bd”,“be”,“bf”,“cd”,“ce”,“cf”]
列表理解是否可行? 我事先不知道列表的维度
答案 0 :(得分:9)
如果你不知道输入的维度,那么你需要使用递归,因为@legoscia说:
cartesian([H]) -> [[A] || A <- H];
cartesian([H|T]) -> [[A|B] || A <- H, B <- cartesian(T)].
1-dim输入“abc”变为[“a”,“b”,“c”],其他一切都是递归。
> cartesian:cartesian(["abc", "def", "ghi"]).
["adg","adh","adi","aeg","aeh","aei","afg","afh","afi",
"bdg","bdh","bdi","beg","beh","bei","bfg","bfh","bfi","cdg",
"cdh","cdi","ceg","ceh","cei","cfg","cfh","cfi"]
编辑:或者更简单但是:让0-dim参数返回包含空集的集合。我认为这也是数学家所能做的。
cartesian([H|T]) -> [[A|B] || A <- H, B <- cartesian(T)];
cartesian([]) -> [[]].
答案 1 :(得分:3)
如果你有两个列表,那么你可以使用这样的列表理解来完成:
1> [[X,Y] || X <- "abc", Y <- "def"].
["ad","ae","af","bd","be","bf","cd","ce","cf"]
如果你有一个任意数量的列表,你可以在递归函数中使用列表推导来完成它。