Generic Lisp: shorthand for initializing a hash table with many records

I'm looking for a possible non verbose portable way to initialize a hash table in Common Lisp. For instance. what works for persistent hash tables, but also for preloading variable hashes. In CLISP, I use:

(defconstant +my-map+ #S(HASH-TABLE :TEST FASTHASH-EQ
  (key1 . "value1")
  ...
  (keyN . "valueN")
))

but unfortunately this format only works on CLISP.

+5
source share
2 answers

You can programmatically build a hash table while reading:

(defvar *ht* #.(let ((ht (make-hash-table)))
                 (loop for (key . value) in
                       '((a . 1) (b . 2) (c . 3))
                       do (setf (gethash key ht) value))
                 ht))

(describe *ht*)

#.used to estimate reading time. Then the compiler will output the hash table to the FASL file.

This can then be compiled:

Using SBCL:

* (compile-file "/tmp/test.lisp")

; compiling file "/private/tmp/test.lisp" (written 24 MAY 2012 10:08:49 PM):
; compiling (DEFVAR *HT* ...)
; compiling (DESCRIBE *HT*)

; /tmp/test.fasl written
; compilation finished in 0:00:00.360
#P"/private/tmp/test.fasl"
NIL
NIL
* (load *)

#<HASH-TABLE :TEST EQL :COUNT 3 {100299EA43}>
  [hash-table]

Occupancy: 0.2
Rehash-threshold: 1.0
Rehash-size: 1.5
Size: 16
Synchronized: no
T
* *ht*

#<HASH-TABLE :TEST EQL :COUNT 3 {100299EA43}>

Creating a hash table as a function:

(defun create-hashtable (alist
                         &key (test 'eql)
                         &aux (ht (make-hash-table :test test)))
  (loop for (key . value) in alist
        do (setf (gethash key ht) value))
  ht)
+6
source

All Articles