我要检查语法对象中是否存在关键字。 关键字后跟一个表达式很容易:
(syntax-parse #'(hello #:world "sunny")
[(_ (~optional (~seq #:world <adjective>:str)))
#'(string-append "Hello world! Today's weather is "
(~? <adjective> "unknown"))])
但是,如果我只想检查关键字是否存在,就没有语法绑定可以检查:
(syntax-parse #'(hello #:world)
[(_ (~optional #:world))
#:with maybe-world (if (attribute #:world) #'" world" #'"") ; doesn't work
#'(string-append "Hello" maybe-world "!")])
如何将#:world
的存在绑定到语法属性?
答案 0 :(得分:2)
您可以使用~and
将语法绑定到属性:
(syntax-parse #'(hello #:world)
[(_ (~optional (~and world? #:world)))
#:with maybe-world (if (attribute world?) #'" world" #'"")
#'(string-append "Hello" maybe-world "!")])
来自文档https://docs.racket-lang.org/syntax/stxparse-patterns.html?q=~and#(elem.(pattern-link.(~7eand._s))):
One use for ~and-patterns is preserving a whole term (including its lexical
context, source location, etc) while also examining its structure.
Syntax classes are useful for the same purpose, but ~and can be lighter weight.