Set of keys from a map

会有一股神秘感。 提交于 2019-12-22 02:02:42

问题


I have a map X and I'm trying to get a set of the keys satisfying a certain condition, something like this:

Map.Keys X
|> Set.filter (fun x -> ...)

...but I cannot find the way to get the keys from F#'s Map collection.


回答1:


Convert your map to sequence of tuples (key,value) first and then map it to a sequence of just keys:

map |> Map.toSeq |> Seq.map fst

FSI sample:

>Map.ofList[(1,"a");(2,"b")] |> Map.toSeq |> Seq.map fst;;
val it : seq<int> = seq [1; 2]

Or alternatively, as ordering of keys likely does not matter you may use more eager method returning the list of all keys. It is also not hard to make it into extension method keys of Microsoft.FSharp.Collections.Map module:

module Map =
    let keys (m: Map<'Key, 'T>) =
        Map.fold (fun keys key _ -> key::keys) [] m



回答2:


For a set of keys you could just do:

let keys<'k, 'v when 'k : comparison> (map : Map<'k, 'v>) =
    Map.fold (fun s k _ -> Set.add k s) Set.empty map



回答3:


Most readable (and probably most efficient, due to not needing previous conversions to Seq or mapping) answer:

let Keys(map: Map<'K,'V>) =
    seq {
        for KeyValue(key,value) in map do
            yield key
    } |> Set.ofSeq


来源:https://stackoverflow.com/questions/19744720/set-of-keys-from-a-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!