common-lisp - Common Lisp 符号中允许使用哪些字符?

标签 common-lisp

common lisp 符号中允许使用哪些字符?你能给出一个正则表达式来匹配它们(或者它们超出了正则语法的描述能力)吗?

我尝试寻找这方面的信息,但我能找到的只是一些examples在 CLHS 中,但没有具体定义什么是合法符号。

编辑:

因此,common lisp 符号可以合法地包含任何字符。

但是,解析器在读取 Lisp 代码时不仅仅接受任何字符。可解析符号的规则是什么?例如。可以作为'引用符号或在'(引用列表)内部提供的符号。

我对从非 Lisp 语言生成和读取非条分隔符号感兴趣。对于我的应用程序来说,使用 [a-zA-Z0-9:&-]+ 就足够了,但我倾向于尽可能准确,这就是为什么我试图确定是否存在可以匹配符号的正则表达式。匹配|定界语法|将是一个额外的好处,但非定界符号就足够了。

这需要是使用(读取)时可以合法加载的符号。答案不是符号可以包含任何字符:

[1]> (read t)
#
*** - READ from #<IO TERMINAL-STREAM>: objects printed as # in view of *PRINT-LEVEL* cannot be read back in

我想知道这里的有效符号的规则或正则表达式,而不用 | 分隔它。

最佳答案

正如 sds 提到的,符号名称可以包含任何字符。给定任何字符串,您都可以使用该名称创建一个符号。然而,根据您的评论,听起来您想知道在相当默认的设置下,什么会被读取为符号。答案仍然是“几乎任何事情”,但也有一些异常(exception)。

HyperSpec 中的相关部分以 2.2 Reader Algorithm 开头,它描述了标记化过程。它详细描述了该过程,但也许最重要的部分是:

When dealing with tokens, the reader's basic function is to distinguish representations of symbols from those of numbers. When a token is accumulated, it is assumed to represent a number if it satisfies the syntax for numbers listed in Figure 2-9. If it does not represent a number, it is then assumed to be a potential number if it satisfies the rules governing the syntax for a potential number. If a valid token is neither a representation of a number nor a potential number, it represents a symbol.

其中提到的图2.9除了在2.3.1 Numbers as Tokens节中,其中表示:

When a token is read, it is interpreted as a number or symbol. The token is interpreted as a number if it satisfies the syntax for numbers specified in the next figure.

因此,该过程实际上是“对流进行标记,对于每个标记,检查它是否是数字,如果不是数字,则它是符号。”我意识到这并没有为符号提供一个干净的语法,但这就是语言的定义方式。如果您坐下来为 Lisp 编写标记器和读取器,您可能会发现这是一种非常方便的方法。您几乎只需要识别哪些字符终止符号,哪些字符开始和结束列表,哪些字符作为空格被消除,以及转义字符是什么。然后,您读取嵌套的标记列表,将每个标记转换为数字或符号(或字符串等)。

也许最简单的方法之一就是,Common Lisp 有一个 *read-base* 变量来控制根据。根据*read-base*的值,有些东西是数字或符号,只有知道完整的 token 是什么以及运行时的当前状态是什么,你才能知道。

CL-USER> 'beef
BEEF
CL-USER> (setf *read-base* 16)
16
CL-USER> 'beef
48879
CL-USER> (setf *read-base* a)   ; set it back to 10, which is now a
10
CL-USER> (setf *read-base* 36)
36
CL-USER> 'hello                 ; a number
29234652
CL-USER> 'hello\ world          ; a symbol
|HELLO WORLD|

关于common-lisp - Common Lisp 符号中允许使用哪些字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33396550/

相关文章:

lisp - 关键字符号和带引号的符号有什么区别?

list - 使用 lisp 中的嵌套列表删除列表的重复元素

parameters - 在 lisp 中按值传递参数

package - 重新定义已删除的包 (Common Lisp)

lisp - 如何遍历 Common Lisp 中的目录?

common-lisp - 在 Common Lisp (SBCL) 中,有没有办法检查原子的各个部分?

common-lisp - 专门研究向量和矩阵

bash - 如何从命令行脚本(或 cron)启动 Common Lisp GTK 应用程序?

lisp - 为什么不同函数之间的谓词命名约定不同?

coding-style - Common Lisp 对象设置函数风格