Lesson 17. Maps, dictionaries, and sets
This lesson should be a fairly easy one as we round off the collection types in F#. So far you’ve looked at collections that model ordered elements of data in some way—sequences, lists, and arrays—that behave similarly to the BCL List or IEnumerable types. You’ll now spend a little time looking at using other collection types in F#:
- Working with the standard Generic dictionary in F#
- Creating an immutable IDictionary
- Using the F#-specific Map type
- Using the F#-specific Set type
F# has several dictionaries available to it. Let’s review the main types now.
You almost certainly already 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. You’ll be happy to know that, as with the majority of the BCL, you can use this class out of the box in F#.
Listing 17.1. Standard dictionary functionality in F#
open System.Collections.Generic let inventory = Dictionary<string, float>() #1 inventory.Add("Apples", 0.33) #2 inventory.Add("Oranges", 0.23) inventory.Add("Bananas", 0.45) inventory.Remove "Oranges" #3 let bananas = inventory.["Bananas"] #4 let oranges = inventory.["Oranges"] #5