3.7 关键字

关键字 值类似于符号(见符号),不过其打印形式带有 #: 前缀。

+The Racket ReferenceReading Keywords一节中阐述了关键字语法的要点。

例如:
> (string->keyword "apple")

'#:apple

> '#:apple

'#:apple

> (eq? '#:apple (string->keyword "apple"))

#t

更确切地说,关键字类似于标识符。标识符可通过引述来产生符号, 而关键字可通过引述来产生值。术语“关键字”会在两种情景下使用,不过有时我们使用 关键字值来更具体地指代引述的关键字表达式的结果或 string->keyword 的结果。正如未引述的标识符不会产生符号,未引述的关键字也不是表达式:

例如:
> not-a-symbol-expression

not-a-symbol-expression: undefined;

 cannot reference an identifier before its definition

  in module: top-level

  internal name: not-a-symbol-expression

> #:not-a-keyword-expression

eval:2:0: #%datum: keyword misused as an expression

  at: #:not-a-keyword-expression

尽管关键字与标识符或符号很相似,但它们却有着不同的用途。 (未引述的)关键字的目的是在参数列表和具体的语法形式中用作特殊标记。 对于运行时标注(flags)和枚举,请使用符号而非关键字。 下面的例子展示了关键字和符号在用法上的区别。

例如:
> (define dir (find-system-path 'temp-dir)) ; 而非 '#:temp-dir
> (with-output-to-file (build-path dir "stuff.txt")
    (lambda () (printf "example\n"))
    ; 可选的 #:mode 可以是 'text'binary
    #:mode 'text
    ; 可选的 #:exists参数可以是 'replace, 'truncate, ...
    #:exists 'replace)