符号 (symbol)
symbol 的写法是用一个单引号开头,例如:'a、'b、'c,这个类型比较抽象,刚接触知道有这么个东西就行,重点是需要用到的时候知道如何去使用。
symbol 实际上是一种指针,每个 symbol 都存在以下几个组成部分(slot):
Print name ( name )
Value
Function binding
Property list
只有 name 是必要的,其他的部分都可以为空,当一个 文本引用 产生时,会创建一个 symbol ,且 Value 会默认为 'unbound。
这段话不知道怎么讲更好,贴一下原文:
The system creates a symbol whenever it encounters a text reference to the symbol for the first time. When the system creates a new symbol, the value of the symbol is set to unbound.
当我们创建一个变量会自动生成与之对应的一个 symbol ,默认值为 'unbound,这个过程是非显式的。
这样,如果需要将一个变量设置为 未定义/未绑定 的状态,则可以将它赋值为 'unbound。
举个例子 ( 重点是这里 ):
给 arg 赋值为 12,然后打印出来。
arg = 12
println( arg )
; 终端会打印 12
复制代码
给 arg 再赋值为 'unbound,然后尝试 print 一下。
arg = 'unbound
println( arg )
; 终端会提示 *Error* eval: unbound variable - arg
复制代码
当一个变量没有被定义过的时候,引用它但是不赋值时运行会报 Error ,但如果只是想判断某个变量是否被定义了,可以使用函数 boundp 去检测目标变量的 symbol name。