gpt4 book ai didi

f# - 在 F# 中寻找 Haskell `group` 替代方案

转载 作者:行者123 更新时间:2023-12-01 17:31:48 24 4
gpt4 key购买 nike

Haskell group 描述如下:http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-List.html#v:group

示例:

group "Mississippi" = ["M","i","ss","i","ss","i","pp","i"]

有简单的 F# 方法吗?

我可以实现类似的东西

let rec sameCounter (data : list<float>) el same (ss : list<float * int>) = 
if data.Length > (el + 1) then
if data.[el] = data.[el + 1] then
sameCounter data (el + 1) <| same + 1 <| ss
else if same > 0 then sameCounter data (el + 1) <| 0 <| (data.[el], same) :: ss
else sameCounter data (el + 1) <| 0 <| ss
else ss
let group d = sameCounter d 0 0 []

但我认为这有点难看,有更好的变体吗?

最佳答案

这是我想出来的,我认为是合理的:

let groupConsecutive sq =
(Array.ofSeq sq, [])
||> Array.foldBack (fun x -> function
| [] -> [[x]]
| xs :: xss ->
if x = List.head xs then
(x :: xs) :: xss
else [x] :: xs :: xss)
// val groupConsecutive : s:seq<'a> -> 'a list list when 'a : equality

groupConsecutive "Mississippi"
// val it : char list list = [['M']; ['i']; ['s'; 's']; ['i']; ['s'; 's']; ['i']; ['p'; 'p']; ['i']]

如果您还希望能够获取和返回无限序列,则需要手动使用GetEnumerator,这会变得更加难看。

关于f# - 在 F# 中寻找 Haskell `group` 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23928218/

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