简体   繁体   中英

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"

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> 
~          

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM