13

Google 提供了大量在 F# 字典(或其他集合)中添加和删除条目的示例。但我没有看到相当于的例子

myDict["Key"] = MyValue;

我试过了

myDict.["Key"] <- MyValue

我也试图将字典声明为

Dictionary<string, mutable string>

以及这方面的几个变体。但是,我还没有找到正确的组合......如果它在 F#中实际上是可能的。

编辑:有问题的代码是:

type Config(?fileName : string) =
    let fileName = defaultArg fileName @"C:\path\myConfigs.ini"

    static let settings =
        dict[ "Setting1", "1";
              "Setting2", "2";
              "Debug",    "0";
              "State",    "Disarray";]

    let settingRegex = new Regex(@"\s*(?<key>([^;#=]*[^;#= ]))\s*=\s*(?<value>([^;#]*[^;# ]))")

    do  File.ReadAllLines(fileName)
        |> Seq.map(fun line -> settingRegex.Match(line))
        |> Seq.filter(fun mtch -> mtch.Success)
        |> Seq.iter(fun mtch -> settings.[mtch.Groups.Item("key").Value] <- mtch.Groups.Item("value").Value)

我得到的错误是:

System.NotSupportedException: This value may not be mutated
   at Microsoft.FSharp.Core.ExtraTopLevelOperators.dict@37-2.set_Item(K key, V value)
   at <StartupCode$FSI_0036>.$FSI_0036_Config.$ctor@25-6.Invoke(Match mtch)
   at Microsoft.FSharp.Collections.SeqModule.iter[T](FastFunc`2 action, IEnumerable`1 sequence)
   at FSI_0036.Utilities.Config..ctor(Option`1 fileName)
   at <StartupCode$FSI_0041>.$FSI_0041.main@()
stopped due to error
4

2 回答 2

28

f# 有两种常见的关联数据结构:

你最习惯的那个,它继承的可变字典,它存在于 BCL 中,并在引擎盖下使用哈希表。

let dict = new System.Collections.Generic.Dictionary<string,int>()
dict.["everything"] <- 42

另一个称为Map并且在常见的功能样式中是不可变的并用二叉树实现。

与会更改字典的操作不同,地图提供了返回新地图的操作,该地图是所请求的任何更改的结果。在许多情况下,在底层不需要制作整个地图的全新副本,因此可以正常共享的部分是。例如:

let withDouglasAdams = Map.add "everything" 42 Map.empty

该值withDouglasAdams将永远保持为“一切”与 42 的关联。所以如果你以后这样做:

let soLong = Map.remove "everything" withDouglasAdams

那么这种“移除”的效果只能通过soLong值可见。

如前所述,F# 的 Map 实现为二叉树。因此查找是 O(log n),而(表现良好的)字典应该是 O(1)。在实践中,基于散列的字典在几乎所有简单(元素数量少,冲突概率低)中往往优于基于树的字典,因为这种字典是常用的。也就是说,Map 的不可变方面可能允许您在字典需要更复杂的锁定或编写更“优雅”且副作用更少的代码的情况下使用它,因此它仍然是一个有用的替代方案。

然而,这不是您问题的根源。dict 'operator' 返回一个明确的不可变IDictionary<K,T>实现(尽管在它的文档中没有说明这一点)。

fslib-extra-pervasives.fs(还要注意键上选项的使用):

let dict l = 
    // Use a dictionary (this requires hashing and equality on the key type)
    // Wrap keys in an Some(_) option in case they are null 
    // (when System.Collections.Generic.Dictionary fails). Sad but true.
    let t = new Dictionary<Option<_>,_>(HashIdentity.Structural)
    for (k,v) in l do 
        t.[Some(k)] <- v
    let d = (t :> IDictionary<_,_>)
    let c = (t :> ICollection<_>)
    let ieg = (t :> IEnumerable<_>)
    let ie = (t :> System.Collections.IEnumerable)
    // Give a read-only view of the dictionary
    { new IDictionary<'key, 'a> with 
            member s.Item 
                with get x = d.[Some(x)]            
                and  set (x,v) = raise (NotSupportedException(
                                            "This value may not be mutated"))
   ...
于 2009-07-29T22:19:04.027 回答
7

你得到什么错误?我尝试了以下,它编译得很好

let map = new System.Collections.Generic.Dictionary<string,int>()
map.["foo"] <- 42

编辑验证此代码是否也可以正常运行。

于 2009-07-29T21:41:58.843 回答