【问题标题】:Hot to declare an empty Map/dictionary?很想声明一个空的地图/字典?
【发布时间】:2019-01-07 12:41:00
【问题描述】:

我想用 Map 初始化一个递归函数。要声明一个带值的只读字典,我们可以这样做:

let dictionary1  = dict [ (1, "a"); (2, "b"); (3, "c") ]       

Try it online!

现在,我想创建一个空字典。如何实现?

我正在寻找类似的东西:

let dictionary1 = {} // <- ok this is js
let (stuff, dictionary2) = parseRec("whatever", dictionary1)

【问题讨论】:

    标签: f#


    【解决方案1】:

    既然你要求地图/字典,这里有两个Map的其他解决方案:

    let dictionary1 : Map<int, string> = Map.empty
    let dictionary1 = Map<int, string> []
    

    source

    【讨论】:

      【解决方案2】:

      你可以这样做:

      let dictionary1  = dict []
      
      for elem in dictionary1 do
         printfn "Key: %d Value: %s" elem.Key elem.Value
      

      这会给你一个空字典。

      printfn 的用法向类型推断引擎揭示了键和值的正确类型。

      如果你想明确,那么你可以通过几种方式指定类型:

      let dictionary1 = dict Seq.empty<int * string>
      let dictionary1 = dict ([] : (int * string) list)
      let dictionary1 = dict [] : System.Collections.Generic.IDictionary<int, string>
      let dictionary1 : System.Collections.Generic.IDictionary<int, string> = dict []
      

      【讨论】:

      • dict Seq.empty&lt;int * string&gt; 和 `dict ([] : (int * string) list)` 在 C# 世界中可以被视为 (IEnumerable&lt;KeyValuePair&gt;).ToDictionary(),不是吗?
      • 嗯,dict 的类型是seq&lt;'K * 'V&gt; -&gt; System.Collections.Generic.IDictionary&lt;'K,'V&gt;,所以任何元组序列都可以用来生成字典。
      【解决方案3】:

      如果您需要 .NET Dictionary,您可以使用 .net Dictionary

      let dictionary1 = new System.Collections.Generic.Dictionary<int, string>()
      

      【讨论】:

      猜你喜欢
      • 2014-07-24
      • 1970-01-01
      • 2015-06-03
      • 1970-01-01
      • 2012-06-11
      • 2016-10-16
      • 2019-08-01
      • 2013-05-16
      • 2023-01-17
      相关资源
      最近更新 更多