gpt4 book ai didi

racket - 如何检查 Racket 语法中是否存在关键字?

转载 作者:行者123 更新时间:2023-12-01 03:07:41 25 4
gpt4 key购买 nike

我想检查语法对象中是否存在关键字。
当关键字后跟一个表达式时,这很容易:

(syntax-parse #'(hello #:world "sunny")
[(_ (~optional (~seq #:world <adjective>:str)))
#'(string-append "Hello world! Today's weather is "
(~? <adjective> "unknown"))])

但是,如果我只想检查关键字是否存在,则不再需要检查语法绑定(bind):
(syntax-parse #'(hello #:world)
[(_ (~optional #:world))
#:with maybe-world (if (attribute #:world) #'" world" #'"") ; doesn't work
#'(string-append "Hello" maybe-world "!")])

如何绑定(bind) #:world 的存在到语法属性?

最佳答案

您可以使用 ~and将语法绑定(bind)到属性:

(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.

关于racket - 如何检查 Racket 语法中是否存在关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55171895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com