gpt4 book ai didi

list - 给定一个 (a * b) 列表,返回一个 (a * b list) 列表

转载 作者:行者123 更新时间:2023-12-04 20:49:42 28 4
gpt4 key购买 nike

也许是一个时髦的标题,但我遇到了以下问题:

给定一个类型为 (a * b) list 的列表,我想创建一个类型为 (a * b list) list 的新列表。一个例子:

给定列表 let testList = [(1,"c");(2,"a");(1,"b")],我的函数应该返回 [( 1, ["c";"b"]; (2, ["a"])]

我有以下内容,但我对如何继续有点困惑:

let rec toRel xs =
match xs with
| (a,b)::rest -> (a,[b])::toRel rest
| _ -> []

最佳答案

可以使用内置函数List.groupBy然后map去除多余的key:

testList |> List.groupBy fst |> List.map (fun (k,v) -> (k, List.map snd v))

// val it : (int * string list) list = [(1, ["c"; "b"]); (2, ["a"])]

否则如果你想继续比赛你可以这样做:

let toRel x = 
let rec loop acc xs =
match xs with
| (k, b) :: rest ->
let acc =
match Map.tryFind k acc with
| Some v -> Map.add k (b::v) acc
| None -> Map.add k [b] acc
loop acc rest
| _ -> acc
loop Map.empty x |> Map.toList

或者使用Option.toList你可以这样写:

let toRel x = 
let rec loop acc xs =
match xs with
| (k, b) :: rest ->
let acc =
let lst = Map.tryFind k acc |> Option.toList |> List.concat
Map.add k (b::lst) acc
loop acc rest
| _ -> acc
loop Map.empty x |> Map.toList

关于list - 给定一个 (a * b) 列表,返回一个 (a * b list) 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46773823/

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