简体   繁体   中英

How can I make a Map[string, obj] in F#?

I am trying to make an immutable map of

in C#, I can turn a dictionary into a readonly one, achieving the same.

but it looks like, in F#, the first element decides the type of the rest of the map.

so I tried something ugly:

Map [
    "key1", value1 |> obj
    "key2", value2 |> obj

or

Map [
    "key1", box value1
    "key2", box value2

is there a better solution where the compiler would automatically box the items?

The problem I am trying to solve is to talk to an external C# library expecting a Dictionary and I'm trying to learn if the F# compiler can do this kind of things.

This question already has an answer , albeit for Dictionary<_,obj> rather than Map<_,obj> .

let (=>) k v = k, box v
// val ( => ) : k:'a -> v:'b -> 'a * obj

Map [ "key1" => 1; "key2" => 'a' ]
// val it : Map<string,obj> = map [("key1", 1); ("key2", 'a')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM