gpt4 book ai didi

list - F# - 将列表拆分为奇偶列表元组(按元素,而不是位置)

转载 作者:行者123 更新时间:2023-12-01 09:16:09 25 4
gpt4 key购买 nike

示例:split [1;3;2;4;7;9];;
输出:([1;3;7;9], [2;4])

我是 F# 的新手,我搞不懂。
无法使用 partition 内置函数。

这是我目前所拥有的:

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 指出我的错误:无法到达的案例和不必要地修改赔率

最佳答案

可以使用内置的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]

请注意,这会以相反的顺序为您提供两个结果列表,因此您可能希望自己反转它们。

关于list - F# - 将列表拆分为奇偶列表元组(按元素,而不是位置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44379239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com