beardc
beardc

Reputation: 21073

Testing whether list elements are strings in CL

I'm trying to learn Common Lisp (sbcl) and getting practice with basic defuns. I'm trying to write one now that adds the lengths of all the strings in a list.

An early step is testing whether the first element is a string. I assumed you could call this with

(stringp (car '(s1 s2)))

where s1 and s2 are strings. Testing s1 with stringp, and asking for the car of the list seem to work ok, but combining them together doesn't give me what I expect:

CL-USER> (car '(s1 s2))
S1
CL-USER> (stringp s1)
T
CL-USER> (stringp (car '(s1 s2)))
NIL

Am I misunderstanding the stringp function, or the way lists work?

Thank you

Upvotes: 2

Views: 121

Answers (2)

Rainer Joswig
Rainer Joswig

Reputation: 139411

The QUOTE prevents the evaluation of its enclosed form. The enclosed form is returned as is.

(car '(s1 s2)) returns S1. Which is a symbol and not a string.

If you evaluate s1, then Lisp returns its value. But that uses another evaluation step.

If you look at s1 as a symbol, then it stays a symbol if you tell Lisp:

CL-USER > 's1
S1

CL-USER > (stringp 's1)
NIL

Upvotes: 2

sepp2k
sepp2k

Reputation: 370455

'(s1 s2) is a list containing the symbols s1 and s2. So (car '(s1 s2)) returns the symbol s1 (as you can see by the fact that the REPL prints S1 and not whatever string is stored in the variable s1. Since a symbol is not a string, stringp returns false.

If you actually use a list of strings, it will work as you expect:

* (car (list s1 s2))
"contents of s1"

* (stringp (car (list s1 s2)))
T

Upvotes: 5

Related Questions