06 / Fundamentals

Maps

A Map stores key-value pairs with fast lookup by key. Maps are created with Map.new() and support insertion, retrieval, membership testing, and key enumeration.

06-maps.nxSource →
// Maps: Map.new(), insert, get, has, size, iterar con keys()

// bool -> texto: int_to_string() espera un int y un bool no se convierte solo,
// así que la conversión se escribe explícita.
fn si_no(b: bool) -> String {
    if b { return "si" }
    return "no"
}

fn main() -> int {
    var capitales: Map = Map.new()

    // Insertar pares clave-valor
    capitales.insert("Argentina", "Buenos Aires")
    capitales.insert("Francia", "Paris")
    capitales.insert("Japon", "Tokio")

    // size
    print("paises: " + int_to_string(capitales.size()))

    // get
    let capital: String = capitales.get("Francia")
    print("Capital de Francia: " + capital)

    // has
    print("tiene Argentina: " + si_no(capitales.has("Argentina")))
    print("tiene Brasil: " + si_no(capitales.has("Brasil")))

    // Iterar claves
    let ks: Array = capitales.keys()
    print("claves (" + int_to_string(ks.length()) + "):")
    for k in ks {
        // El tipo de elemento de un Array que devuelve un builtin no se infiere:
        // sin esta anotación, "  " + k concatena el puntero, no el texto.
        let clave: String = k
        print("  " + clave)
    }

    return 0
}
Outputstdout
paises: 3
Capital de Francia: Paris
tiene Argentina: si
tiene Brasil: no
claves (3):
  Francia
  Japon
  Argentina

How it works

Maps in Nyx are created with Map.new() — there is no map literal syntax (it would be ambiguous with block expressions). The recipe declares the map with var by convention, but let works the same for inserting: in Nyx let and var govern whether the binding can be reassigned, not whether the map it points to can be mutated.

The .insert(key, value) method adds or updates a key-value pair. .get(key) retrieves the value for a key, returning the stored value as a String (or the appropriate type). If the key does not exist the program panics with a message naming the key; use .has(key) to check first, or .get_or(key, default) to supply a fallback.

.has(key) returns a bool, and a bool is not an int in Nyx: passing it straight to int_to_string does not compile, so the recipe routes it through the small si_no helper to print it as text. .size() returns the number of entries currently in the map.

.keys() returns an Array of all keys in the map, and the iteration order of a hash map is not the insertion order. An Array does not carry the type of its elements either, so the loop body binds each key with let clave: String = k before printing it — without that annotation the concatenation would emit the address of the key instead of its text.