Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set of keys from a map

Tags:

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.

like image 755
Suugaku Avatar asked Nov 02 '13 17:11

Suugaku


People also ask

How do you set a map key?

HashMap put() Method in Java put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map.

What are keys in map?

A map key is an inset on a map that explains the symbols, provides a scale, and usually identifies the type of map projection used. Technically, the key is part of the map legend. The key explains the symbols, while the legend holds the key and other information.

Can we use set as key in map?

A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on a such a map.


1 Answers

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 
like image 104
Gene Belitski Avatar answered Oct 20 '22 14:10

Gene Belitski