gpt4 book ai didi

collections - 该算法已经存在高阶函数了吗?

转载 作者:行者123 更新时间:2023-12-04 20:32:43 25 4
gpt4 key购买 nike

我想出了我在 F# 代码中需要的这个简单算法(将元组列表转换为键的映射集合到列表):

let MergeIntoMap<'K,'V when 'K: comparison>(from: seq<'K*'V>): Map<'K,seq<'V>>=
let keys = from.Select(fun (k,v) -> k)
let keyValuePairs = seq {
for key in keys do
let valsForKey = from.Where(fun (k,v) -> key = k).Select(fun (k,v) -> v) |> seq
yield key,valsForKey
}
keyValuePairs |> Map.ofSeq

示例输入:
[ ("a", 1); ("b", 2), ("a", 3) ]

输出:
dict [ ("a", [1; 3]), ("b", [2]) ]

我在想这一定是已经在 BCL 或 F# 的高阶函数集中的东西了?如果是的话,有人可以引用我吗?因为我确信我的代码不是很有效,因为它是......

最佳答案

看来你想得到类似的东西

let toGroupMap x = 
x
|> Seq.groupBy fst
|> Seq.map
(fun (k,v) -> k, v |> Seq.map snd |> Seq.toArray)
|> Map.ofSeq

金融情报服务:
val toGroupMap : x:seq<'a * 'b> -> Map<'a,'b []> when 'a : comparison
val input : (string * int) list = [("a", 1); ("b", 2); ("a", 3)]
val output : Map<string,int []> = map [("a", [|1; 3|]); ("b", [|2|])]

编辑

如书面 Fyodor Soikin在评论中,有一个扩展方法 ToLookup ,这可能满足您的需求。
open System.Linq

let output = input.ToLookup(fst, snd)

您可以阅读 here关于 ILookup 和 IDictionary 接口(interface)的区别

关于collections - 该算法已经存在高阶函数了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42465510/

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