地图中的键集 [英] Set of keys from a map

查看:63
本文介绍了地图中的键集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个地图X,我正在尝试获取满足一定条件的一组键,如下所示:

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 -> ...)

...但是我找不到从F#的Map集合中获取密钥的方法.

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

推荐答案

转换您的首先将映射到元组(key,value)的序列,然后将其映射到仅键序列:

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示例:

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

或者,由于键的顺序可能无关紧要,您可以使用更急切的方法返回所有键的list.将它添加到Microsoft.FSharp.Collections.Map模块的扩展方法keys中也不难:

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

这篇关于地图中的键集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆