Maps in Nim

Maps in Nim are used to store key-value pairs. Here’s an example of how to work with maps in Nim:

```nim
import tables

proc main() = 
    # Creating an empty map
    var m = initTable[string, int]()

    # Setting key/value pairs
    m["k1"] = 7
    m["k2"] = 13

    # Printing the map
    echo "map: ", m

    # Getting a value for a key
    let v1 = m["k1"]
    echo "v1: ", v1

    # Accessing a non-existent key returns a default value
    let v3 = m.getOrDefault("k3", 0)
    echo "v3: ", v3

    # Getting the number of key/value pairs
    echo "len: ", m.len

    # Deleting a key/value pair
    m.del("k2")
    echo "map: ", m

    # Removing all key/value pairs
    m.clear()
    echo "map: ", m

    # Checking if a key exists in the map
    let prs = m.hasKey("k2")
    echo "prs: ", prs

    # Declaring and initializing a map
    var n = initTable[string, int]({"foo": 1, "bar": 2})
    echo "map: ", n

    # Checking map equality
    let n2 = initTable[string, int]({"foo": 1, "bar": 2})
    if n == n2:
        echo "n == n2"

main()

Explanation:

  1. var m = initTable[string, int]() initializes an empty map where the keys are of type string and the values are of type int.
  2. m["k1"] = 7 and m["k2"] = 13 set key-value pairs in the map.
  3. echo "map: ", m prints the entire map showing all its key-value pairs.
  4. let v1 = m["k1"] retrieves the value for the key "k1".
  5. let v3 = m.getOrDefault("k3", 0) retrieves the value for the key "k3" or returns 0 if the key does not exist.
  6. m.len returns the number of key-value pairs in the map.
  7. m.del("k2") removes the key-value pair for the key "k2".
  8. m.clear() removes all key-value pairs from the map.
  9. m.hasKey("k2") checks if the key "k2" exists in the map.
  10. var n = initTable[string, int]({"foo": 1, "bar": 2}) declares and initializes a new map.
  11. let n2 = initTable[string, int]({"foo": 1, "bar": 2}) declares and initializes another map.
  12. if n == n2 checks if the two maps are equal.

To run the program, save the code in a file with a .nim extension and run it using the Nim compiler:

$ nim compile --run your_file.nim

Here’s the expected output:

map: {"k1": 7, "k2": 13}
v1: 7
v3: 0
len: 2
map: {"k1": 7}
map: {}
prs: false
map: {"foo": 1, "bar": 2}
n == n2

Next example: Functions.