给定(a * b)列表,返回(a * b列表)列表

时间:2017-10-16 15:28:04

标签: list f#

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

给定类型LexicallyDeclaredNames的列表,我想创建一个类型为var的新列表。一个例子:

鉴于列表var,我的函数应返回(a * b) list

我有以下内容,但我有点坚持如何继续:

(a * b list) list

1 个答案:

答案 0 :(得分:8)

您可以使用内置函数List.groupBy,然后映射以删除冗余密钥:

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