简体   繁体   English

Lisp - 仅当符号不是字符串时才将符号转换为字符串

[英]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? 有没有办法将符号转换为字符串,只要它不是lisp中的字符串?

It should work like this: 它应该像这样工作:

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

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

Use the function STRING . 使用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. 您可以使用format函数进行转换。 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: 虽然它比列出的其他选项慢,但它可以在其他数据类型上工作,控制upcase / downcase等。因此对于开发或代码的非内部循环部分,这可能对您有用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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