我有几个与如下结构相匹配的函数:
(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)]))))我想把这个抽象出来,这样结构的一个函数
(matcher (struct-name1返回值) (struct-name2返回值).)
即(matcher (线(+ 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])这有可能吗?
发布于 2015-06-06 10:54:43
您可以扩展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)发布于 2015-06-10 07:19:51
这是我想要做的,但现在它太具体了:
( 1)即使我只想匹配2个结构,也必须始终使用4点、线、弧、路径语法。
2)宏是在一个文件中定义的,如果我想使用语法a、b、c、d内的另一个文件中定义的函数,它将给出一个错误“模块中的未绑定标识符”。我想要的是一种混合的能力,既可以集成局部函数,也可以从比赛的左边提取变量,但我还没有弄清楚如何做到这一点。
(define-syntax match-struct
(lambda (stx)
(syntax-case stx ()
[(_ (dot a) (line b) (arc c) (path d))
(with-syntax ([tmp0 (syntax->datum #'a)]
[tmp1 (syntax->datum #'b)]
[tmp2 (syntax->datum #'c)])
#'(lambda (a-struct)
(match a-struct
[(dot highlighted selected visible layer p) tmp0]
[(line highlighted selected visible layer p1 p2) tmp1]
[(arc highlighted selected visible layer center radius start end p1 p2 p3) tmp2]
[(path highlighted selected visible layer entities) (d entities)])))])))https://stackoverflow.com/questions/30638222
复制相似问题