有人可以提出更好和/或更优雅的实现方式:
让每个xs =
让REC的每个acc左,右=
与之匹配
| []-> acc
|右-> let new_left =左@ [List.hd右]
让next = List.tl对
让结果=(List.hd右),左@下一个
每个'(结果:: acc)new_left下一个
每个'[] [] xs
它这样做:
>每个[1..3] ;;
val it:(int * int list)list = [(3,[1; 2]); (2,[1; 3]); (1,[2; 3])]
此函数也可以反向返回结果。想法是将所有元素作为元组包含元素和其余元素列表。
最佳答案
此处的语义略有不同,但是从您提供的Set
的示例可能很合适:
let each xs =
let X = set xs
[ for x in xs -> (x, X - set [x]) ]
> fsi.AddPrinter( fun (x:Set<int>) -> sprintf "%A" (Set.to_list x))
> each [1..3];;
> val it : (int * Set<int>) list = [(1, [2; 3]); (2, [1; 3]); (3, [1; 2])]
// Edited as per comments.
关于list - F#中列表的所有选择-更优雅,更简单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1189563/