F#字典,更改连续项 [英] F# dictionary, change consecutive items

查看:84
本文介绍了F#字典,更改连续项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

#light

打开 系统

打开 System.Collections通用

let initItems = [ | for in 1..20 ->

let initItems = [| for i in 1..20 -> (i, 0M) |]

             |>字典

let 可变 dItems:IDictionary< int,十进制> = initItems

let mutable dItems: IDictionary<int, decimal> = initItems

我有一个可变的字典dItem,为它分配了一些初始值.但是,稍后,我需要更改一些值:每次更改3个连续键的值.例如:第一次,我想更改(1,0M),(2,0M),(3, 0M)更改为(1,1M),(2,2M),(3,3M),第二次,我想将(11,0M),(12,0M),(13,0M)更改为(11, 1M),(12、2M),(13、3M).

I have a mutable dictionary dItems, I have some initial values assigned to it.  However, later on, I need to change some values: each time change values for 3 consecutive keys.  For example: the first time, I want to change (1, 0M), (2, 0M), (3, 0M) to (1, 1M), (2, 2M), (3, 3M) and the second time, I want to change (11, 0M), (12, 0M), (13, 0M) to (11, 1M), (12, 2M), (13, 3M).

对于更改,键/值对,键始终连续3个,每次修改字典时值都在变化,字典中的元素总数固定为20个元素.

For the change, the key/value pairs, the keys are always consecutive in 3, the values are changing each time when modifying the dictionary, the total dictionary elements are fixed at 20 elements.

我认为我可以通过 强制 方式:遍历每个字典元素,如果该键在3个连续的键之内,则删除键值对,然后添加新的键值对.

I think I can easily do this via imperative way: loop through each dictionary element, if the key is within the 3 consecutive keys, then remove the key value pairs, then add the new key value pair.

但是我该如何以实用的方式做到这一点?

谢谢,

推荐答案

如果您有一个不可变的集合或至少将其视为不可变的,则功能性方法将最有效.然后,您将编写一个函数,该函数接受字典和起始索引,并执行您描述的转换并返回新字典 修改的元素.您可能要使用F#映射类而不是IDictionary.

The functional approach would work best if you have an immutable collection or at least treat it as immutable. Then you'd write a function that takes the dictionary and the starting index and does the transformations you describe and returns a new dictionary with elements modified.  You might want to use the F# map class instead of IDictionary.


这篇关于F#字典,更改连续项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆