typestar

Map y Set en F#

Colecciones inmutables con clave y de únicos; cada add devuelve otra.

// Map and Set are immutable: every add returns a new collection.
let stores = Map [ "Willow", 14; "Bramble", 9 ]
let updated = stores |> Map.add "Clover" 18

printfn "Clover stored: %d" updated.["Clover"]
printfn "Missing hive: %A" (updated |> Map.tryFind "Thistle")

updated
|> Map.iter (fun hive jars -> printfn "%s: %d jars" hive jars)

let spring = Set ["Willow"; "Bramble"]
let autumn = Set ["Bramble"; "Clover"]
printfn "Surveyed twice: %A" (Set.intersect spring autumn)
printfn "Whole yard: %d hives" (Set.union spring autumn |> Set.count)

Cómo funciona

  1. Map.add entrega un mapa más grande; el original queda.
  2. Map.tryFind devuelve un Option en vez de lanzar.
  3. Set.intersect y union hablan álgebra de censos.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
14
Caracteres a escribir
547
Tokens
128
Ritmo de tres estrellas
65 tpm

Al ritmo de tres estrellas de 65 tokens por minuto, este intento toma unos 118 segundos.

Escribe este fragmento

Paso 1 de 3 en Colecciones; paso 16 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →