In F# programs we often need to map keys to values—a color name might have an index value. We could use a dict
to make these links.
A dict
is read-only: we create it once and cannot modify its contents. We use the dict
keyword. A Dictionary
, which can be changed, may also be used when mutability is needed.
Let us begin with a simple example. We create a "colors" dictionary with string
keys and int
values. This is a read-only sequence of key-value pairs.
dict
. We use printfn
with an "%A" to print the int
value returned.// Create a dictionary with 2 key-value pairs. let colors = dict["blue", 40; "red", 700] // Print value of "blue" key. printfn "%A" (colors.Item("blue")) // Print value of "red" key. printfn "%A" (colors.Item("red"))40 700
Count
, for
-loopA dict
has many features—it supports all of the methods from the IDictionary
interface
. Often we must count, or iterate over, a dict
's contents.
Count
returns an int
. Here we see our dict
has two key-value pairs. We store this value in the constant "c."for-in
loop to print all the values of the dict
. We use a do keyword to indicate the start of the loop body.// Create a dictionary with dict keyword. let sizes = dict["small", 0; "large", 10] // Get count of pairs and display it. let c = sizes.Count printfn "%A" c // Loop over pairs in the dictionary. // ... Display each KeyValuePair. for pair in sizes do printfn "%A" pair2 [small, 0] [large, 10]
Keys
With this property we get a collection of the keys in the dict
. With this collection (which is not a list) we can use a function like Seq.iter
. Here we print all the keys.
let places = dict["Canada", 10; "Germany", 20] // Get keys in a collection. let keys = places.Keys // Display all keys with labels. Seq.iter (fun key -> printfn "Key = %A" key) keysKey = "Canada" Key = "Germany"
A dict
is read-only. It is immutable. This means we cannot set or add items (keys or values) to it. To add keys we must create a new dict
.
// Create a lookup table. let lookup = dict["100", false; "200", true] // This causes an exception. lookup.Item("300") <- falseUnhandled Exception: System.NotSupportedException: This value cannot be mutated
We can use the dict
keyword with existing key-value pairs. We can create these pairs with tuple syntax. Then we just pass them into the dict
expression.
[<EntryPoint>] let main argv = let pair = ("carrot", "orange") let pair2 = ("apple", "red") // Use dict with Key-Value pairs already created. let fruit = dict[pair; pair2] // Write the Count. printfn "COUNT: %d" fruit.Count 0COUNT: 2
A dict
is immutable in F#. This helps with functional programming, but sometimes we want a more versatile lookup table. We use a Dictionary
for this purpose.
Special F# constructs like dict
can be used with other constructs like the tuple syntax. We can use a 2-item tuple to create an entry in a dict
. Immutability is retained.