gpt4 book ai didi

f# - F Sharp 将元组列表转换为映射元组列表

转载 作者:行者123 更新时间:2023-12-02 21:15:33 24 4
gpt4 key购买 nike

声明一个将对列表转换为关系的函数。

type Relation<'a,'b> = ('a * 'b list) list

基本上,转动这个:

[(2,"c");(1,"a");(2,"b")]

进入此:

[(2,["c";"b"]);(1,["a"])]

以这种形式:

toRel:(’a*’b) list -> Rel<’a,’b> 

有什么想法吗?这不是作业,只是自学,考虑到该表格不允许积累,这让我有点困惑。

最佳答案

[(2,"c");(1,"a");(2,"b")]
|> List.groupBy fst
|> List.map (fun (x,y)->x,List.map snd y)

结果:

[(2, ["c"; "b"]); (1, ["a"])]

类型推断对于 toRel 位来说很方便:

let toRel xs = 
xs
|> List.groupBy fst
|> List.map (fun (x,y)->x,List.map snd y)

用法:

toRel [(2,"c");(1,"a");(2,"b")]

关于f# - F Sharp 将元组列表转换为映射元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43868941/

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