首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在球拍中抽离比赛

在球拍中抽离比赛
EN

Stack Overflow用户
提问于 2015-06-04 08:02:33
回答 2查看 93关注 0票数 4

我有几个与如下结构相匹配的函数:

代码语言:javascript
复制
(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) (路径实体))将返回:

代码语言:javascript
复制
(match a-struct
        [(struct* line  ([x1 x1]))              (+ 1 x1)]
        [(struct* arc   ([radius radius]))      radius]
        [(struct* point ([x x]))                x]
        [(struct* path  ([entities entities]))  entities])

这有可能吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-06-06 10:54:43

您可以扩展match。定制模式是用define-match-expander定义的。

假设你有这个结构

代码语言:javascript
复制
(struct line (x1 y1 x2 y2))

你观察到你使用的是匹配模式

代码语言:javascript
复制
(line _ y1 _ y2)

再三。你更喜欢写

代码语言:javascript
复制
(line* y1 y2)

使用define-match-expander,您可以将(line* y1 y2)转换为(line _ y1 _ y2)

下面是一个完整的例子:

代码语言:javascript
复制
(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)])

产出如下:

代码语言:javascript
复制
'(1 3)
票数 1
EN

Stack Overflow用户

发布于 2015-06-10 07:19:51

这是我想要做的,但现在它太具体了:

( 1)即使我只想匹配2个结构,也必须始终使用4点、线、弧、路径语法。

2)宏是在一个文件中定义的,如果我想使用语法a、b、c、d内的另一个文件中定义的函数,它将给出一个错误“模块中的未绑定标识符”。我想要的是一种混合的能力,既可以集成局部函数,也可以从比赛的左边提取变量,但我还没有弄清楚如何做到这一点。

代码语言:javascript
复制
(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)])))])))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30638222

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档