This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Use assoc with argument of type string

3 posts · 3866 views

Hi everybody,
I have this association-list:
(defvar base-list (list (cons 'a 0) (cons 2 'c)))
I have to call assoc when my argument is of type string.

So for the pair
 (A . 0)
I have to convert "a" to a symbol, and for the pair
(2 . C)
I have to convert "2" to a symbol. How can I do that?

This should work like this:
CL-USER 28 : 1 > (assoc (convert-string-to-symbol "a") base-list)
(A . 0)
CL-USER 28 : 1 > (assoc (convert-number-to-symbol "2") base-list)
(2 . C)
I tried using intern but got NIL:
CL-USER 29 : 1 > (assoc (intern "a") base-list)
NIL
Thanks a lot

Re: Use assoc with argument of type string

ou were close with intern; you just had the case wrong. Try this:

> (assoc (intern "A") base-list)
(A . 0)
Note that here the name-as-string is capitalized.

Alternately, you could use find-symbol to look for an existing symbol by name:

> (assoc (find-symbol "A") base-list)
(A . 0)
The key here is that when you wrote your original defvar form, the reader read the string "a" and—by virtue of the current readtable case—converted the symbol name to be uppercase. Symbols with names of different case are not equal. It just so happens that at read time the reader is projecting what you wrote (lowercase) to something else (uppercase).

You can inspect the current case conversion policy for the current reader using the readtable-case function:

> (readtable-case *readtable*)
:UPCASE
To learn more about how the readtable case and the reader interact, see the discussion in section 23.1.2 of the Hyperspec.

Re: Use assoc with argument of type string

Because CL is internally case-sensitive and ordinary symbols (without vertical bars) are in upper case. Thus this will work:
(assoc (intern "A") base-list)
Furthermore an ordinary symbol can't have digit chars at beginning.
The cons (2 . C) can be got by:
(assoc 2 base-list)
// Result of
(intern "a")
is a symbol |a| and simirlarly
(intern "2")
is a symbol |2|.
cl-2dsyntax is my attempt to create a Python-like reader. My mirror of CLHS (and the dark themed version). Temporary mirrors of aferomentioned: CLHS and a dark version.