F# - 从整数输入生成元组列表

F# - generating a list of tuples from integer input

我应该 return 来自整数输入的元组列表。 例如: output' 4 应该 return 一个元组列表:

[(1, 1);
(2, 1); (2, 2);
(3, 1); (3, 2); (3, 3);
(4, 1); (4, 2); (4, 3); (4, 4)]

目前我得到

 [(1, 1); (1, 2); (1, 3); (1, 4);
 (2, 1); (2, 2); (2, 3); (2, 4);
 (3, 1);(3, 2); (3, 3); (3, 4);
 (4, 1); (4, 2); (4, 3); (4, 4)]

我目前拥有的:

let output' x =
    let ls= [1..x]
    ls |> List.collect (fun x ->[for i in ls -> x,i])    
output' 4

我不知道如何获得所需的输出。任何帮助,将不胜感激。

您可以添加过滤器:

...
|> List.filter (fun (a, b) -> a >= b)`

let output x =
    [ for i in 1..x do
      for j in 1..i do yield (i,j)
    ]

在 F# 中,它们主要使用序列,因此这里有一个序列驱动的惰性解决方案:

let output' max =
    let getTuples x = 
        seq { 1 .. x }
        |> Seq.map (fun y -> (x, y))

    seq { 1 .. max }
    |> Seq.map getTuples

如果您需要列表,请将 seq { 1 .. x } 替换为 [ 1 .. x ]。 它仍然比循环更实用。