gpt4 book ai didi

f# - 在 F# 中折叠列表

转载 作者:行者123 更新时间:2023-12-02 08:45:43 24 4
gpt4 key购买 nike

我有一个非常琐碎的任务,但我不知道如何使解决方案更漂亮。
目标是采用 List 并根据它们是否通过谓词返回结果。结果应该分组。这是一个简化的示例:

谓词:isEven
输入:[2; 4; 3; 7; 6; 10; 4; 5]
输出:[[^^^^]......[^^^^^^^^]..]

这是我目前的代码:

let f p ls =
List.foldBack
(fun el (xs, ys) -> if p el then (el::xs, ys) else ([], xs::ys))
ls ([], [])
|> List.Cons // (1)
|> List.filter (not << List.isEmpty) // (2)

let even x = x % 2 = 0

let ret =
[2; 4; 3; 7; 6; 10; 4; 5]
|> f even
// expected [[2; 4]; [6; 10; 4]]

这段代码看起来可读性不是很好。另外,我不喜欢第 (1) 和 (2) 行。有没有更好的解决方案?

最佳答案

这是我的看法。你首先需要一些辅助函数:

// active pattern to choose between even and odd intengers
let (|Even|Odd|) x = if (x % 2) = 0 then Even x else Odd x

// fold function to generate a state tupple of current values and accumulated values
let folder (current, result) x =
match x, current with
| Even x, _ -> x::current, result // even members a added to current list
| Odd x, [] -> current, result // odd members are ignored when current is empty
| Odd x, _ -> [], current::result // odd members starts a new current

// test on data
[2; 4; 3; 7; 6; 10; 4; 5]
|> List.rev // reverse list since numbers are added to start of current
|> List.fold folder ([], []) // perform fold over list
|> function | [],x -> x | y,x -> y::x // check that current is List.empty, otherwise add to result

关于f# - 在 F# 中折叠列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12657569/

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