Search code examples
common-lisphashtablesymbolscase-sensitive

auto-generate key for hash table in common lisp


I would like to generate sequential keys that I can use across a number of hash tables. I will call them 'id1','id2' etc. If ht is my hash table then I would like to make symbols from strings as keys. To add an entry to the hash table I want to so something like:

(setf (gethash (make-symbol "id1") ht) 1)

And then access it again with

(gethash 'id1 ht)

I don't think make-symbol is giving me what I want, and the key 'id1' sn't recognised.

What is the best way to make this key?


Solution

  • Error: symbol should be in a package and needs the correct case

    In your case we have:

    CL-USER 24 > (symbol-name (make-symbol "id0"))
    "id0"
    
    CL-USER 25 > (symbol-package (make-symbol "id0"))
    NIL
    

    Make sure that you think about the following:

    • intern the symbol in a package
    • intern the symbol in the correct package
    • make sure the symbol has the correct name with the correct case
    • write symbols with the case you intend to use, possibly you need to escape the symbol to preserve the case

    Examples:

    uppercased symbol and lowercase symbol name -> not eq

    CL-USER 26 > (eq 'id0 (intern "id0" "CL-USER"))
    NIL
    

    uppercased symbol and uppercase symbol name -> is eq

    CL-USER 27 > (eq 'id0 (intern "ID0" "CL-USER"))
    T
    

    an escaped&lowercase symbol and a lowercase symbol name -> is eq

    CL-USER 28 > (eq '|id0| (intern "id0" "CL-USER"))
    T