Essentially I'd say that you'll have to use (typep var 'string-type)
, but there is no such type as string as far as I known.
Determining a type via type-of results in
(type-of "rowrowrowyourboat")
> (SIMPLE-ARRAY CHARACTER (17))
which is hardy a type I could look for in a generic way as looking for just SIMPLE-ARRAY
wouldn't do any good:
(typep "rowrowrowyourboat" 'simple-array)
> t
(typep (make-array 1) 'simple-array)
> t
And using a intuitive the hack of dynamically determining the type of an example string doesn't do any good either as they will not be of the same length (most of the time)
(typep "rowrowrowyourboat" (type-of "string"))
> nil
So I wonder what is the canonical way to check whether a given variable is of type string?
Most types has a predicate in CL and even if a string is a sequence of chars it exists a function, stringp , that does exactly what you want.
(stringp "getlydownthestream") ; ==> T
It says in the documentation that that would be the same as writing
(typep "ifyouseeacrocodile" 'string) ; ==> T
Your question has several misconceptions. Usually in Lisp variables don't have a type.
Repeat: Variables in Lisp have no types .
You can ask if some Lisp value is of some type or what type it has. Lisp objects have types attached.
Common Lisp has no type 'string'? Why don't you look into the documentation? It is easy.
Common Lisp HyperSpec: http://www.lispworks.com/documentation/HyperSpec/Front/index.htm
Symbol Index: http://www.lispworks.com/documentation/HyperSpec/Front/X_Symbol.htm
Symbol Index for S: http://www.lispworks.com/documentation/HyperSpec/Front/X_Alph_S.htm
STRING: http://www.lispworks.com/documentation/HyperSpec/Body/a_string.htm#string
System Class STRING: http://www.lispworks.com/documentation/HyperSpec/Body/t_string.htm
So Common Lisp has a type STRING
.
The Strings Dictionary also lists other string types: BASE-STRING
, SIMPLE-STRING
, SIMPLE-BASE-STRING
.
I'm using LispWorks, so the returned types look a bit different:
CL-USER 20 > (type-of "foo")
SIMPLE-BASE-STRING
CL-USER 21 > (typep "foo" 'string)
T
CL-USER 22 > (stringp "foo")
T
CL-USER 23 > (subtypep 'simple-base-string 'string)
T
T
CL-USER 24 > (let ((var "foo")) (typep var 'string))
T
Secret: variables in Common Lisp can be typed, but that is another story.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.