繁体   English   中英

F#错误,Map包括Dictionary

[英]F# error, Map including Dictionary

我制作了一个包含几个词典的地图。 每次收到数据时,我都会在Map中找到相应的字典,然后在这个字典中添加新信息。 但问题是每次我尝试添加信息时,它都不会仅在相应的字典中添加它,而是将其添加到地图中的所有字典中。 拜托,我变得疯了。

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
            ()

正如评论中所提到的,如果您正在学习函数式编程,那么最好的方法是使用不可变数据结构 - 在这里,您可以使用将索引映射到嵌套映射的映射(其中包含您需要的键值信息) 。

尝试使用以下示例:

// 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)

使用上述功能,您现在可以创建初始地图,然后向其添加各种信息:

// 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