For loop 无法更改For循环中字典的值?

For loop 无法更改For循环中字典的值?,for-loop,dictionary,f#,For Loop,Dictionary,F#,所以我对F有点陌生,但我有C的背景。我正在编写一个代码,它将遍历字典,向每个元素添加1,如果该值超过100,则向列表添加一个元素。这是我的密码: //Early on in the code let variables = new Dictionary<string, int>() let variablecnt = new Dictionary<string, int>() let trash = new List<int>() //Later on in

所以我对F有点陌生,但我有C的背景。我正在编写一个代码,它将遍历
字典
,向每个元素添加1,如果该值超过100,则向列表添加一个元素。这是我的密码:

//Early on in the code
let variables = new Dictionary<string, int>()
let variablecnt = new Dictionary<string, int>()
let trash = new List<int>()

//Later on in the code at a higher encapsulation level
    for KeyValue(j, k) in variablecnt do
        variablecnt.[j] <- k+1
        if variablecnt.[j]=100 then
            trash.Add(0)
            variables.Remove(j) |> ignore
它给出的行号对应于:

variablecnt.[j] <- k+1

variablecnt.[j]也许你应该试试这样的东西

我有意避开标准的.NET容器和可变的添加/删除,而是为您提供一个F#风格的解决方案来演示语法(我认为当您是新手时,最好避免重蹈覆辙)

//初始变量计数
设variablecnt=dict(k,v+1)
//将字典拆分为包含以下值的twp列表:
//分别小于、大于或等于100
设splitAt100=
Seq.map(keyVal)//映射到KeyValuePairs
>>Seq.toList//转换为列表
>>List.partition(fun(k,v)->v<100)//基于v<100拆分为元组
//将splitat100函数应用于变量计数
设lThan100,grEq100=splitAt100变量cnt
//变量是键值对的字典,其中值小于100
让变量=lThan100 |>dict
//trash是一个0的列表,其长度等于具有100+个值的键值对的数量
让垃圾桶=grEq100 |>List.map(乐趣->0)

如果你想要一个可变的
变量
字段,那么一旦它被生成,你就可以用这个新字段来更新原始字段。

这与F#无关。在任何.NET语言中,在对集合进行迭代时都不能对其进行变异。啊……我不确定在C#中如何从未遇到过这样的错误。我不经常使用字典(我更经常使用数组和列表)。
variablecnt.[j] <- k+1
// initial variable count
let variablecnt = dict <| Seq.empty<string*int>

/// Convert from KeyValuePair to tuple of (k*v)
let keyVal =
    function
    |KeyValue(k, v) -> (k, v+1)

// split dictionary into twp lists containing values which are
// less than or greater than or equal to 100 respectively
let splitAt100 = 
    Seq.map (keyVal) // map to KeyValuePairs
    >> Seq.toList // convert to list
    >> List.partition (fun (k,v) -> v < 100) // split into tuples based on v < 100

// apply the splitat100 function to the variable count
let lThan100, grEq100 = splitAt100 variablecnt 
// variables is a dictionary of the key value pairs, where the values are less than 100
let variables = lThan100 |> dict
// trash is a list of 0s equal in length to the number of key value pairs with 100+ values
let trash = grEq100 |> List.map (fun _ -> 0)