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 wheth开发者_如何学运维er 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
'(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
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
精彩评论