The*_*ost 2 f# functional-programming list simplify
有人可以提出更好和/或更优雅的实现:
let each xs =
let rec each' acc left right =
match right with
| [] -> acc
| right -> let new_left = left @ [List.hd right]
let next = List.tl right
let result = (List.hd right), left @ next
each' (result::acc) new_left next
each' [] [] xs
它做到了:
> each [1..3];; val it : (int * int list) list = [(3, [1; 2]); (2, [1; 3]); (1, [2; 3])]
此函数也可以反向返回结果.我们的想法是将所有元素作为元组,包含元素和rest元素列表.
这里的语义略有不同,但从你给出的例子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.
Run Code Online (Sandbox Code Playgroud)