fsprojects/FSharpx.Collections


PersistentHashMap

A Map is a collection that maps keys to values. Hash maps require keys that correctly support GetHashCode and Equals. Hash maps provide fast access (log32N hops). Count is O(1).

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
// Create an empty PersistentHashMap and add some elements
PersistentHashMap<int,string> map =
    PersistentHashMap<int, string>.Empty()
        .Add(42,"hello")
        .Add(99, "world");

Console.WriteLine(map[42]); // hello
Console.WriteLine(map[99]); // world

// Check no. of elements in the PersistentHashMap
Console.WriteLine(map.Length);  // 2

PersistentHashMaps are immutable and therefor allow to create new version without destruction of the old ones.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
PersistentHashMap<int, string> map2 = 
    map
     .Add(104, "!")
     .Add(42, "hi");  // replace existing value

Console.WriteLine(map2[42]); // hi
Console.WriteLine(map[42]);  // hello            

Console.WriteLine(map.Length);  // 2
Console.WriteLine(map2.Length); // 3

// remove the last element from a PersistentHashMap
PersistentHashMap<int, string> map3 = map2.Remove(104);

Console.WriteLine(map3.Length); // 2
Fork me on GitHub