Maps in Chapel

Maps are Chapel’s way of managing a collection of key/value pairs. Below is an example of how to work with maps in Chapel.

use Map;
use IO;

proc main() {
    // Create an empty map
    var m: map(string, int);

    // Set key/value pairs using typical syntax
    m["k1"] = 7;
    m["k2"] = 13;

    // Print the map to show all its key/value pairs
    writeln("map: ", m);

    // Get a value for a key
    var v1 = m["k1"];
    writeln("v1: ", v1);

    // If the key doesn’t exist, the default value of the value type is returned
    var v3 = m.getOrDefault("k3", 0);
    writeln("v3: ", v3);

    // The length of the map can be obtained
    writeln("len: ", m.size);

    // Remove key/value pairs from the map
    m.remove("k2");
    writeln("map: ", m);

    // Clear all key/value pairs from the map
    m.clear();
    writeln("map: ", m);

    // Check if a key is present in the map
    var prs = m.contains("k2");
    writeln("prs: ", prs);

    // Declare and initialize a new map with key/value pairs
    var n: map(string, int) = map(tuple("foo", 1), tuple("bar", 2));
    writeln("map: ", n);

    // Using a utility function to compare maps
    var n2: map(string, int) = map(tuple("foo", 1), tuple("bar", 2));
    if n == n2 {
        writeln("n == n2");
    }
}

To run the program, save the code in a .chpl file and use chpl to compile and execute it.

$ chpl map-example.chpl -o map-example
$ ./map-example
map: { ("k1" => 7) }
v1: 7
v3: 0
len: 1
map: { ("k1" => 7) }
map: { }
prs: false
map: { ("bar" => 2), ("foo" => 1) }
n == n2

Chapel provides a robust set of functions in the Map module to help with common map operations like initialization, querying, and comparing maps. This example demonstrates some basic usage of maps in Chapel.