F#中是否有库函数组合来自不同列表的元素

Ste*_*t_R 4 f# combinatorics

我想要一个f获取列表列表的函数,并返回通过从每个列表中取一个元素所做的所有可能组合的元组列表.

例如

f [["A";"B";"C"];[1;2]]
Run Code Online (Sandbox Code Playgroud)

会给出结果:

[("A",1);("A",2);("B",1);("B",2);("C",1);("C",2)]
Run Code Online (Sandbox Code Playgroud)

和:

f [[onions;peas];[mash;fries];[chicken;steak]]
Run Code Online (Sandbox Code Playgroud)

会给:

[(onions,mash,chicken);(onions,mash,steak);(onions;fries;chicken) ... (peas,fries,steak)]
Run Code Online (Sandbox Code Playgroud)

我正在考虑滚动我自己,但感觉必须有一个库函数比我的拇指拳法更好地优化,但我似乎无法通过谷歌搜索找到任何东西(我可能不知道正确的组合术语,所以保持打不同的组合方法和功能)

Mar*_*ann 7

像CaringDev一样,我认为没有任何标准库函数可以做到这一点.我认为其中一个原因是它们会有不同的类型.

[["A";"B";"C"];[1;2]]来自OP的代码甚至不编译,因为字符串值的使用向编译器指示这是一个嵌套的字符串列表,但是[1;2]是一个整数列表.

它可以用元组来完成,但这是一对的组合函数与三元组的组合函数不同,依此类推.

也就是说,实现这些功能是微不足道的:

let combine2 xs ys = [
    for x in xs do
    for y in ys do
    yield x, y ]

let combine3 xs ys zs = [
    for x in xs do
    for y in ys do
    for z in zs do
    yield x, y, z ]
Run Code Online (Sandbox Code Playgroud)

例子:

> combine2 ["A";"B";"C"] [1;2];;
val it : (string * int) list =
  [("A", 1); ("A", 2); ("B", 1); ("B", 2); ("C", 1); ("C", 2)]
> combine3 ["onions"; "peas"] ["mash"; "fries"] ["chicken"; "steak"];;
val it : (string * string * string) list =
  [("onions", "mash", "chicken"); ("onions", "mash", "steak");
   ("onions", "fries", "chicken"); ("onions", "fries", "steak");
   ("peas", "mash", "chicken"); ("peas", "mash", "steak");
   ("peas", "fries", "chicken"); ("peas", "fries", "steak")]
Run Code Online (Sandbox Code Playgroud)