F# Mutable Dictionary

In this article, you will learn how to create and use F# mutable dictionaries. This tutorial aims to provide a basic introduction to creating, initializing, and updating a dictionary, as well as demonstrate how to iterate over the values in a dictionary, add, remove, and update its elements.

F# has several advantages over other programming languages, such as immutability and expressiveness. However, there are situations when mutable data structures, such as dictionaries, can be more convenient.

F# provides a system for creating and modifying mutable dictionaries using the System.Collections.Generic.Dictionary <‘TKey, ‘TValue> class.



Creating of a Mutable Dictionary

The new keyword is used to create mutable dictionaries, which are then passed to the lists constructor to become mutable.

This can be demonstrated by the following example:

Example: 

// Creating a Dictionary open System.Collections.Genericlet actors = new Dictionary<string, string>() actors.Add("Jennifer Aniston", "1969") actors.Add("Kevin Hart", "1979") actors.Add("Matt LeBlanc", "1967") actors.Add("Morgan Freeman", "1937") actors.Add("Samuel L. Jackson", "1948")printfn "Dictionary – actors: %A" actors

Output:

Dictionary - actors: seq
[[Jennifer Aniston, 1969]; [Kevin Hart, 1979]; [Matt LeBlanc, 1967];
[Morgan Freeman, 1937]; ...]

The Dictionary(TKey,TValue) Class

The Dictionary(TKey, TValue) class refers to a set of keys and values that are separated by commas.

Here is a table that shows the properties, constructors and methods that make up the List(T) class as listed below:

PropertiesOverview
ComparerProvides the IEqualityComparer(T) that determines whether or not the keys in the dictionary are equal.
CountThis function returns the number of key/value pairs that are present in the Dictionary(TKey,TValue).
ItemThe value associated with the specified key can be retrieved or set using this method.
KeysThe result of this method is a collection that contains the keys in the Dictionary(TKey, TValue).
ValuesThe function returns a collection containing the values in the Dictionary(TKey, TValue).

ConstructorsOverview
Dictionary(TKey, TValue)()An instance of the Dictionary(TKey, TValue) class is created when the constructor is called with an empty instance, the default initial capacity, and the equality comparer for the key type as the default.
Dictionary(TKey, TValue)(IDictionary(TKey, TValue))Assigns an instance of the Dictionary(TKey, TValue) class to a key type; the dictionary (TKey and TValue) is populated with elements copied from the IDictionary(TKey, TValue) class, using the default equality comparer for the key type.
Dictionary(TKey, TValue)(IEqualityComparer(TKey))In this method, it will create a new instance of the Dictionary(TKey, TValue) class that has the default initial values, will be empty, will have a default capacity, and will use the specified IEqualityComparer(T).
Dictionary(TKey, TValue)(Int32)The Dictionary(TKey, TValue) class is created using the default equality comparer for the key type and initializes an empty instance of that class with the specified initial capacity and an empty instance with the specified initial capacity.
Dictionary(TKey, TValue)(IDictionary(TKey, TValue), IEqualityComparer(TKey))The Dictionary(TKey, TValue) class is initialized with the elements of the IDictionary(TKey, TValue) class copied from the specified Dictionary(TKey, TValue). An equality comparer is also defined as IEqualityComparer(T).
Dictionary(TKey, TValue)(Int32, IEqualityComparer(TKey))An instance of the Dictionary(TKey, TValue) class is initialized with an empty string, with an initial capacity specified by the specified parameter, and it is configured to use the specified value of IEqualityComparer(T).
Dictionary(TKey, TValue)(SerializationInfo, StreamingContext)The idictionary(TKey, TValue) class is used to serialize a set of data into a single instance of the class.

MethodsOverview
AddThe dictionary is added to with the key and value you specify.
ClearThe following method removes all of the keys and values from the Dictionary(TKey, TValue).
ContainsKeyAs demonstrated in the following code, the following method removes all of the keys and values from the Dictionary(TKey, TValue).
ContainsValueThere is a method that determines whether a particular value is present in the Dictionary(TKey, TValue).
Equals(Object)Obtains a comparison between the specified object and the current object by comparing it with the specified object. This property is inherited from the object.
FinalizeThe garbage collector allows the container object to attempt to free up resources before it can be reclaimed for reusing by doing other cleanup operations. (Inherited from an object.)
GetEnumeratorThe Following is the return value of the function that iterates through the Dictionary(TKey, TValue).
GetHashCodeThis function has the function of serving as the default hash function. (It inherits from the Object class).
GetObjectDataUpon implementing the System.Runtime.Serialization.ISerializable interface, the Dictionary(TKey, TValue) instance is returned with all the data it needs for serialization.
GetTypeThe current instance’s type is returned by this method. (Inherited from an object.)
MemberwiseCloneThis method will create a shallow copy of the current Object. (Inherited from the object.)
OnDeserializationWhen the deserialization process is complete, it raises the deserialization event and returns to the callback function. Defines the interface System.Runtime.Serialization.ISerializable.
RemoveThis function deletes the value associated with the specified key from the Dictionary(TKey, TValue).
ToStringThe function returns a string containing the name of the current object. (Inherited from an object.)
TryGetValueThis method returns the value associated with the key specified in the request.

Example: 

// Creating a Dictionary open System.Collections.Genericlet actors = new Dictionary<string, string>() actors.Add("Jennifer Aniston", "1969") actors.Add("Kevin Hart", "1979") actors.Add("Matt LeBlanc", "1967") actors.Add("Morgan Freeman", "1937") actors.Add("Samuel L. Jackson", "1948")printfn "Dictionary – actors: %A" actors printfn "\nTotal Number of Actors: %d" actors.Count printfn "\nThe keys: %A" actors.Keys printfn "\nThe Values: %A" actors.Values

And the result will be as follows:

Dictionary - actors: seq
[[Jennifer Aniston, 1969]; [Kevin Hart, 1979]; [Matt LeBlanc, 1967];
[Morgan Freeman, 1937]; ...]
Total Number of Actors: 5
The keys: seq ["Jennifer Aniston"; "Kevin Hart"; "Matt LeBlanc"; "Morgan Freeman"; ...]
The Values: seq ["1969"; "1979"; "1967"; "1937"; ...]

Example Explanation

  • We first open the System.Collections.Generic namespace that contains the Dictionary <TKey, TValue> class which we use to create a dictionary. Then we create a new mutable dictionary with string keys and string values using the Dictionary <TKey, TValue> class and store it in a variable called actors.
  • To add key-value pairs to the actors dictionary, we use the Add method of the Dictionary <TKey, TValue> class to add five key-value pairs.
  • We then use the printfn function to print the actors dictionary, the number of actors in the dictionary using the Count property, the keys in the dictionary using the Keys property, and the values in the dictionary using the Values property. We use the %A format specifier with printfn to print the values of complex objects such as dictionaries and lists.

If you found our article on F# Mutable Dictionary informative and helpful, we would love to hear your feedback! Please feel free to share your thoughts and opinions by reacting below. Thank you for reading!

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *