Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# efficient way to convert Map into Dict (and vice versa)

Tags:

dictionary

f#

I didn't find any native function to do the conversion from Dict into Map and viceversa. (Something like Map.ofDict or Dict.ofMap.) Main reason being maps are immutable while dictionaries are not.

Have I missed something?

like image 992
Fagui Curtain Avatar asked Feb 16 '16 00:02

Fagui Curtain


1 Answers

There isn't a convenient function to go from dictionary to map but there is a built in dict function which converts from a sequence of tuples to an IDictionary<'a,'b>, see: https://msdn.microsoft.com/en-us/library/ee353774.aspx.

The simplest way I know to do the dictionary to map conversion is:

let dictToMap (dic : System.Collections.Generic.IDictionary<_,_>) = 
    dic 
    |> Seq.map (|KeyValue|)  
    |> Map.ofSeq

The reverse is easy with the dict function:

let mapToDict map =
    map 
    |> Map.toSeq
    |> dict

Note that the above function returns an IDictionary, the implementation of which is both internal to the FSharp.Core library and not mutable.

If you want to get to a standard .NET mutable dictionary, you use the constructor which accepts an IDictionary, Map implements IDictionary so this step is very straightforward.

let mapToMutDict map =
    map :> System.Collections.Generic.IDictionary<_,_>
    |> System.Collections.Generic.Dictionary
like image 137
TheInnerLight Avatar answered Oct 05 '22 04:10

TheInnerLight