Lisp - Convert symbol to string only if not already a string

Is there a way to convert symbol to string only if it is not already a string in lisp?

It should work like this:

(only-if-convertion 'ABC) => "ABC"

(only-if-convertion "ABC") => "ABC"

Answers


Use the function STRING.

CL-USER > (string "FOO")
"FOO"

CL-USER > (string 'FOO)
"FOO"

CL-USER> (defun symbol-or-string-to-string (x)
       (typecase x
         (symbol (symbol-name x))
         (string x)
         (otherwise (error "Wrong type"))))
SYMBOL-OR-STRING-TO-STRING
CL-USER> (symbol-or-string-to-string "foo")
"foo"
CL-USER> (symbol-or-string-to-string 'foo)
"FOO"
CL-USER> (symbol-or-string-to-string #())
; Evaluation aborted.
CL-USER> 

But the idea of converting it repetitively sounds odd. Can you show why are you needing to do it?


You can use the format function to do the conversion. Granted it's slower than the other options listed, but it can work on other data types, controls upcase/downcase, etc. So for development, or non-inner-loop portions of the code, this could be useful for you:

CL-USER>
(format nil "~a" "str")
"str"
CL-USER>
(format nil "~a" 'str)
"STR"
CL-USER> 
(format nil "~(~a~)" 'str)
"str"
CL-USER>
(format nil "~(~a~)" "str")
"str"
CL-USER> 
~          

Need Your Help

How to find the screen size of two monitors using wx.displaySize()

python wxpython multiple-monitors

I want to get the screen size for two monitors using wxPython.

What's a good way to detect wrap-around in a fixed-width message counter?

c++ c udp integer overflow

I'm writing a client application to communicate with a server program via UDP. The client periodically makes requests for data and needs to use the most recent server response. The request messag...