gpt4 book ai didi

macros - Racket 中的嵌套宏

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:47 25 4
gpt4 key购买 nike

我希望能够像这样编写嵌套表达式:

(AND/OR expr1 op1 expr2 AND/OR expr3 op2 expr4 and so on)

其中 AND/OR 本质上是 AND 或 OR。但我希望能够写出无限多的。我正在使用 define-syntax 来尝试实现这一点,但我不确定如何接受无限量的嵌套表达式。

不要介意我示例中的 expr 和 op,那部分我可以自己处理。我只想知道如何接受无限嵌套。

例子:

(SELECT somecolumns
FROM sometable
WHERE something
AND/OR something
AND/OR (something AND/OR something)
AND/OR ...)

最佳答案

正如 Asumu 所说,一般来说,处理 s 表达式更简单,至少是为了确保正确的运算符优先级,但对于一些简单的情况,syntax-rules 的模式匹配(和 syntax-parse 和 co) 使用剩余参数和递归匹配使这变得容易:

#lang racket
(define-syntax parse-args
(syntax-rules (AND) ; treat AND as a literal
[(_)
; no more argument, return value:
'()]

[(_ (arg1 AND in-rst ...))
; Composed argument found, call parse-args recursively:
(parse-args arg1 AND in-rst ...)]

[(_ arg1 AND rst ...)
; AND operator found, parse left side and rest
(list 'and
; parse the argument (may be composed or not):
(parse-args arg1)
; then parse the rest of the arguments:
(parse-args rst ...))]

[(_ arg)
; in case the argument is not composed or does not contain AND, don't parse it
arg]))

;; TESTS:
(parse-args 'a AND ('b AND 'bb) AND 'c AND 'f)
; -> '(and a (and (and b bb) (and c f)))

(parse-args 'a AND ('b AND 'bb))
; -> '(and a (and b bb))

但是,请注意,在添加其他运算符时,上述代码可能变得不切实际。

编辑:与选择宏一起:

(define-syntax SELECT
(syntax-rules (FROM WHERE)
[(_ select FROM from WHERE where ...)
(list 'Select select 'From from 'Where (parse-args where ...))]))

; TEST:
(SELECT 'somecolumns
FROM 'sometable
WHERE 'something1
AND 'something2
AND ('something3 AND 'something4)
AND 'blop)
; ->
#;'(Select
somecolumns
From
sometable
Where
(and something1
(and something2
(and (and something3 something4) blop))))

同样,模式匹配允许在正确的点切割列表以获得其余参数

关于macros - Racket 中的嵌套宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21080734/

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