在 Common Lisp 中如何将 char 转换为符号?

pat*_*glu 3 lisp list common-lisp

这里是完全口齿不清的初学者。

我想知道如何将字符转换为符号。我想要的只是转换#\aa

这是我到目前为止所做的:

(defun convert(char)
(if(eq char #\a)
    (setq char 'a))
    char)
Run Code Online (Sandbox Code Playgroud)

这个实际上是有效的,但我不想添加 26 个条件(字母表中的字母)并制作一个冗长的愚蠢代码。

我还想知道 common lisp 中是否有任何函数可以将字符列表转换为符号列表,例如:(#\h #\e #\l #\l #\o)to (h e l l o)?我已经找到internmake-symbol与之相关,但它们需要字符串作为参数。

Rai*_*wig 6

CL-USER 230 > (intern (string #\Q))
Q
NIL

CL-USER 231 > (intern (string #\q))
\q
NIL
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您的代码有很多必要的改进:

(defun convert(char)   ; 
(if(eq char #\a)       ; use EQL instead of EQ for characters
                       ; indentation is wrong
    (setq char 'a))    ; indentation is wrong
    char)              ; indentation is wrong
Run Code Online (Sandbox Code Playgroud)

最好写成:

(defun convert (char)
  (if (eql char #\a)
      'a
      char))
Run Code Online (Sandbox Code Playgroud)

或者

(defun convert (char)
  (case char
    (#\a 'a)
    (#\b 'b)
    (otherwise char)))
Run Code Online (Sandbox Code Playgroud)

如上所述,“真正”的解决方案是:

(defun convert (char)
  (intern (string char)))
Run Code Online (Sandbox Code Playgroud)

  • 它们是转义字符,以确保符号可以在符号名称中保留小写字符。 (2认同)
  • @sushibossftw:请注意,`|a|` 与 `\a` 是相同的符号:` (eq '|a| '\a)` 为 true。反斜杠转义下一个字符,而“|...|”转义小节之间的所有字符。我认为实现可以在打印机中自由使用。需要它们是因为(使用默认阅读器设置)`(symbol-name 'a)` 是 `"A"`。 (2认同)