示例:split [1;3;2;4;7;9];;
输出:([1;3;7;9], [2;4])
我是F#的新手,我无法弄明白
无法使用partition
内置功能。</ p>
这是我到目前为止所做的:
let rec split xs =
match xs with
| [] -> [], []
| xs -> xs, []
| xh::xt -> let odds, evens = split xt
if (xh % 2) = 0 then xh::odds, xh::evens
else xh::odds, evens
固定代码:
let rec split xs =
match xs with
| [] -> [], []
| xh::xt -> let odds, evens = split xt
if (xh % 2) = 0 then odds, xh::evens
else xh::odds, evens
*感谢@TheInnerLight指出我的错误:无法访问的案例和不必要的修改赔率
答案 0 :(得分:8)
您可以使用内置的List.partition
功能
let splitOddEven xs =
xs |> List.partition (fun x -> x % 2 <> 0)
splitOddEven [1;3;2;4;7;9];; val it : int list * int list = ([1; 3; 7; 9], [2; 4])
如果你想要一个递归实现,我可能会采用这样的尾递归实现:
let splitOddEven xs =
let rec splitOddEvenRec oddAcc evenAcc xs =
match xs with
| [] -> oddAcc, evenAcc
| xh::xt ->
if (xh % 2) = 0 then splitOddEvenRec oddAcc (xh :: evenAcc) xt
else splitOddEvenRec (xh :: oddAcc) evenAcc xt
splitOddEvenRec [] [] xs
splitOddEven [1;3;2;4;7;9]
请注意,这将以相反的顺序为您提供两个结果列表,因此您可能希望自己反转它们。