2. F# - Mutable Dictionary
• You know the System.Collections.Generic.Dictionary type
from C# or VB .NET.
• This acts as a standard lookup collection, allowing fast
retrieval of values based on a unique key.
• The Dictionary<'TKey, 'TValue> class is the mutable
equivalent of the F# map data structure and contains many of
the same functions.
• a special kind of set that associates the values with key.
3. F# - Mutable Dictionary
1. Creating a dictionary
2. Adding items to the dictionary
3. Removing an item from the dictionary
4. Retrieving an item
5. Trying to access an item that doesn’t exist—
exception is raised
4. 1. Creating a Dictionary
Created new keyword and calling the constructor
open System.Collections.Generic
let dict = new Dictionary<string, string>()
dict.Add("1", "Ronak")
dict.Add("2","Rishita")
dict.Add("3","Robin")
dict.Add("4","Ruchita")
printfn "Dictionary - students: %A" dict
Dictionary - students: seq
[[1, Ronak]; [2, Rishita];
[3, Robin]; [4, Ruchita]]
O/P
5. Properties
Comparer used to determine equality of keys for the dictionary.
Count Gets the number of key/value pairs
Item Gets or sets the value associated with the specified
key.
Keys Gets a collection containing the keys
Values Gets a collection containing the values
6. Example: Properties
open System.Collections.Generic
let dict = new Dictionary<string, string>()
dict.Add("1", "Ronak")
dict.Add("2","Rishita")
dict.Add("3","Robin")
dict.Add("4","Ruchita")
printfn "Dictionary - students: %A" dict
printfn "Total Number of Students: %d" dict.Count
printfn "The keys: %A" dict.Keys
printf"The Values: %A" dict.Values
7. Example: Properties-Output
Dictionary - students: seq
[[1, Ronak]; [2, Rishita]; [3, Robin]; [4, Ruchita]]
Total Number of Students: 4
The keys: seq ["1"; "2"; "3"; "4"]
The Values: seq ["Ronak"; "Rishita"; "Robin"; "Ruchita"]
8. Methods
Add Adds the specified key and value to the dictionary.
Clear Removes all keys and values
Remove Removes the value with the specified key
ContainsKey Determines whether the Dictionary(TKey, TValue)
contains the specified key.
ContainsValue Determines whether the Dictionary(TKey, TValue)
contains a specific value.
9. F# - Mutable Dictionary
[<Measure>]
type amu
type Atom = { Name : string; Weight : float<amu> }
open System.Collections.Generic
let periodicTable = new Dictionary<string, Atom>()
periodicTable.Add( "H", { Name = "Hydrogen"; Weight = 1.0079<amu> })
periodicTable.Add("He", { Name = "Helium"; Weight = 4.0026<amu> })
periodicTable.Add("Li", { Name = "Lithium"; Weight = 6.9410<amu> })
periodicTable.Add("Be", { Name = "Beryllium"; Weight = 9.0122<amu> })
periodicTable.Add( "B", { Name = "Boron "; Weight = 10.811<amu> })
printfn "Dictionary - AMU: %A" periodicTable