简体   繁体   中英

How can I use a map as a type in F#?

I have the following:

Map [
        "A", new Dictionary<int64, int64 * float>()
        "B", new Dictionary<int64, int64 * float>()
]

and I would like a dictionary of those, something like:

let a = 
    new Dictionary<
        string,
        Map [
                "A", new Dictionary<int64, int64 * float>()
                "B", new Dictionary<int64, int64 * float>()
        ]>()

How to I get the type for the map to create the dictionary?

It is not entirely clear whether your question is how to write the type of the dictionary you want or whether you are asking how to construct a value of this type. Map is a generic type Map<'K, 'V> , much like the type of the Dictionary, so to write the type you'd use:

Dictionary<string, Map<string, Dictionary<int64, int64 * float>>>

To create a value, you can write the full type, or you can use the fact that F# can often infer the type arguments for you and so you can replace them with _ . For example:

let map = 
  Map [
      "A", new Dictionary<int64, int64 * float>()
      "B", new Dictionary<int64, int64 * float>()
  ]

let a = new Dictionary<_, _>(dict ["first", map])

I would also add that dictionary of maps of dictionaries is a pretty incomprehensible type. It would probably be a good idea to extract some of those into simple named classes that convey some idea about the meaning of the type.

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