gpt4 book ai didi

racket - 在 Racket 中抽象客场比赛

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

我有几个函数与看起来像这样的结构相匹配:

(define (get-bounding-y struct-lst)
(flatten (for/list ([i struct-lst])
(match i
[(line _ _ _ _ _ y1 _ y2) (list y1 y2)]
[(arc _ _ _ _ _ y radius _ _ _ _ _ _ _ _) (list (+ y radius) (- y radius))]
[(point _ _ _ _ _ y) (list y)]
[(path _ _ _ _ path-list) (get-bounding-y path-list)]))))

我想把它抽象出来,以便结构的功能

(匹配器 (struct-name1 返回值) (struct-name2 返回值) ...)

即(匹配器(线(+ 1 x1))(弧半径)(点x)(路径实体))
将返回:
(match a-struct
[(struct* line ([x1 x1])) (+ 1 x1)]
[(struct* arc ([radius radius])) radius]
[(struct* point ([x x])) x]
[(struct* path ([entities entities])) entities])

那可能吗?

最佳答案

您可以扩展 match .自定义模式定义为 define-match-expander .

假设你有结构

(struct line (x1 y1 x2 y2))

并且您观察到您正在使用匹配模式
(line _ y1 _ y2)

一遍又一遍。你更喜欢写
(line* y1 y2)

使用 define-match-expander你可以转 (line* y1 y2)进入 (line _ y1 _ y2) .

这是一个完整的例子:
(define-match-expander line*
(lambda (stx)
(syntax-case stx ()
[(_line* y1 y2)
#'(line _ y1 _ y2)])))

(match (line 0 1 2 3)
[(line* y1 y2) (list y1 y2)])

输出是:
'(1 3)

关于racket - 在 Racket 中抽象客场比赛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30638222/

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