typestar

Tablas hash en Lisp

Un estante de especias con claves de cadena, que necesita :test 'equal y no el predicado por defecto.

;; :TEST 'EQUAL makes string keys work; the default EQL only matches
;; numbers, characters, and identical objects.
(defvar *shelf* (make-hash-table :test 'equal))

(setf (gethash "cumin" *shelf*) 3)
(setf (gethash "saffron" *shelf*) 1)
(setf (gethash "paprika" *shelf*) 2)

;; The third argument to GETHASH is the value to report for a key
;; that is not on the shelf.
(defvar *cumin* (gethash "cumin" *shelf*))
(defvar *cloves* (gethash "cloves" *shelf* 0))

(format t "~a spices, cumin ~a, cloves ~a~%"
        (hash-table-count *shelf*) *cumin* *cloves*)

;; MAPHASH walks every pair, in no order you should count on.
(maphash (lambda (spice jars) (format t "~a x~a~%" spice jars)) *shelf*)

Cómo funciona

  1. (make-hash-table :test 'equal) compara claves por contenido y (setf (gethash "cumin" *shelf*) 3) guarda un conteo.
  2. (gethash "cloves" *shelf* 0) aporta un valor por defecto para una clave ausente.
  3. (hash-table-count *shelf*) informa el tamaño y maphash recorre cada par en orden no especificado.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
18
Caracteres a escribir
686
Tokens
89
Ritmo de tres estrellas
70 tpm

Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 76 segundos.

Escribe este fragmento

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

← Anterior Siguiente →