Constantine
Constantine

Reputation: 164

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

Upvotes: 1

Views: 128

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243051

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

Upvotes: 4

Related Questions