How to I check whether a given variable value is of type string
Asked Answered
P

2

5

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?

Photofluorography answered 1/9, 2013 at 14:48 Comment(0)
C
9

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
Calliope answered 1/9, 2013 at 15:31 Comment(0)
S
4

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.

Servia answered 1/9, 2013 at 15:46 Comment(1)
i meant (of course) the value of the variable - will correct thatPhotofluorography

© 2022 - 2024 — McMap. All rights reserved.