Racket 中模式匹配时的替代方案
我想匹配 Racket(以前称为 PLT 方案)中的以下两个列表之一:
'(somename : (_ptr o sometype))
或
'(somename : (_ptr io sometype))
如您所见,唯一的区别是嵌入列表中的文字 'o 和 'io。
我可以看到两种基本方法可以做到这一点。
要么:
(match myexpr
[(list name ': (list '_ptr 'o _)) name]
[(list name ': (list '_ptr 'io _)) name]
[_ 0])
这看起来像是重复的工作,但非常清楚。或者:
(match myexpr
[(list name ': (list '_ptr mode _))
(if (or (eq? mode 'o)
(eq? mode 'io))
name
0)]
[_ 0])
它避免了几乎重复的模式,但不太清晰。
我的问题是,有没有一种方法可以指定球拍模式匹配中的替代方案,类似于 {'o | 'io}?如果不是,上面概述的两种方式中哪一种是最惯用的 Racket 方式?
I want to match one of the following two lists in Racket (formerly PLT Scheme):
'(somename : (_ptr o sometype))
or
'(somename : (_ptr io sometype))
As you can see, the only difference is the literals 'o and 'io in the embedded list.
I can see two basic ways to do this.
Either:
(match myexpr
[(list name ': (list '_ptr 'o _)) name]
[(list name ': (list '_ptr 'io _)) name]
[_ 0])
which seems like duplication of the effort, but is very clear. Or:
(match myexpr
[(list name ': (list '_ptr mode _))
(if (or (eq? mode 'o)
(eq? mode 'io))
name
0)]
[_ 0])
which avoids the almost duplicated patterns, but is much less clear.
My question is, is there a way to specify alternatives in racket pattern matching, something along the lines of {'o | 'io}? And, if not, which of the two ways outlined above would be the most idiomatic Racket way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
or
模式(或'o'io)
。当然,不要忘记所有这些都已记录。Use an
or
pattern(or 'o 'io)
. And of course, don't forget that all of this is documented.