typestar

Actualizar mapas anidados en Clojure

Lee y reescribe un inventario de herramientas de dos niveles por rutas de claves, sin anidar a mano.

;; get-in walks a path of keys through nested maps and returns a
;; default when the path runs out early.
(def inventory
  {:tools {:hammer {:on-hand 4 :bin "A1"}
           :chisel {:on-hand 0 :bin "A3"}}})

(println (format "hammers %d" (get-in inventory [:tools :hammer :on-hand])))
(println (format "bolts %d" (get-in inventory [:parts :bolt :on-hand] 0)))

;; assoc-in writes a value at a path, building maps along the way.
;; update-in instead applies a function to whatever sits there, with
;; any extra arguments passed after the current value.
(def stocked (assoc-in inventory [:tools :chisel :on-hand] 6))
(def sold (update-in stocked [:tools :hammer :on-hand] - 3))
(def moved (update-in sold [:tools :chisel :bin] str "-back"))

(println (format "hammers now %d, chisel bin %s"
                 (get-in sold [:tools :hammer :on-hand])
                 (get-in moved [:tools :chisel :bin])))

Cómo funciona

  1. (get-in inventory [:tools :hammer :on-hand]) recorre una ruta de claves, y el 0 final vale cuando la ruta falta.
  2. (assoc-in inventory [:tools :chisel :on-hand] 6) escribe un valor en la ruta y devuelve un mapa nuevo.
  3. (update-in stocked [:tools :hammer :on-hand] - 3) aplica - al conteo que ya está, con 3 como argumento extra.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
19
Caracteres a escribir
855
Tokens
130
Ritmo de tres estrellas
65 tpm

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

Escribe este fragmento

Paso 2 de 3 en Estado y records; paso 23 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →