简体   繁体   English

F#错误,Map包括Dictionary

[英]F# error, Map including Dictionary

I have made a Map which includes several Dictionaries. 我制作了一个包含几个词典的地图。 Everytime I receive a data, I will find the corresponding dictionary in the Map, and then add new information in this dictionary. 每次收到数据时,我都会在Map中找到相应的字典,然后在这个字典中添加新信息。 But the problem is every time I try to add information , it won't add it only in the corresponding dictionary, instead it will add it into all the dictionaries in the map. 但问题是每次我尝试添加信息时,它都不会仅在相应的字典中添加它,而是将其添加到地图中的所有字典中。 please , i am becoming crazy. 拜托,我变得疯了。

while datareceive do 
    let refdictionary = ref totalmap.[index]   //totalmap has a lot of Dictionary, which is indexed by "index"
    let dictionnarydata = totalmap.[index]
    if dictionnarydata.ContainsKey(key1) then
            ........
        else
            refdic.Value.Add(key1,num)   //if the corresponding dictionary does not have such information, then add it in it
            ()

As mentioned in the comments, if you are learning functional programming, then the best approach is to use immutable data structures - here, you could use a map that maps the index to a nested map (which contains the key value information that you need). 正如评论中所提到的,如果您正在学习函数式编程,那么最好的方法是使用不可变数据结构 - 在这里,您可以使用将索引映射到嵌套映射的映射(其中包含您需要的键值信息) 。

Try playing with something like the following sample: 尝试使用以下示例:

// Add new item (key, num pair) to the map at the specified index
// Since totalMap is immutable, this returns a new map!
let addData index (key:int) (num:int) (totalmap:Map<_, Map<_, _>>) = 
  // We are assuming that the value for index is defined
  let atIndex = totalmap.[index]
  let newAtIndex = 
    // Ignore information if it is already there, otherwise add
    if atIndex.ContainsKey key then atIndex
    else atIndex.Add(key, num)
  // Using the fact that Add replaces existing items, we 
  // can just add new map in place of the old one
  totalmap.Add(index, newAtIndex)

Using the above function, you can now create initial map and then add various information to it: 使用上述功能,您现在可以创建初始地图,然后向其添加各种信息:

// Create an int-indexed map containing empty maps as values
let totalmap = Map.ofSeq [ for i in 0 .. 10 -> i, Map.empty ]
totalmap
|> addData 0 1 42
|> addData 0 1 32
|> addData 1 10 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM