Haskell 模式匹配对称情况
假设我有一个像这样的 haskell 表达式:
foo (Nothing, Just a) = bar a
foo (Just a, Nothing) = bar a
是否有任何 haskell 语法可以折叠这些情况,以便我可以匹配任一模式并指定 bar a
作为两者的响应?或者这是我能得到的最简洁的吗?
Suppose I have a haskell expression like:
foo (Nothing, Just a) = bar a
foo (Just a, Nothing) = bar a
Is there any haskell syntax to collapse those cases, so I can match either pattern and specify bar a
as the response for both? Or is that about as succinct as I can get it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的代码比示例更复杂,您可能需要执行类似的操作,使用
Maybe
的Alternative
实例和PatternGuards
扩展(Haskell2010 的一部分)。如果您不熟悉它,
<|>
如果有,则选择最左边的Just
,否则返回Nothing
,导致模式防护失败。If your code is more complex than your example, you might want to do something like this, using the
Alternative
instance forMaybe
and thePatternGuards
extension (part of Haskell2010).In case you are not familiar with it,
<|>
picks the left-mostJust
if there is one and returnsNothing
otherwise, causing the pattern guard to fail.这与 Haskell 中一样简洁。在 ML 中,有一个满足您需要的语法(通过编写多个模式,这些模式绑定相同的变量,彼此相邻,并在最后一个模式后面用正文分隔),但在 Haskell 中,有不是。
That's as succinct as it gets in Haskell. In ML there is a syntax for what you want (by writing multiple patterns, which bind the same variables, next to each other separated by
|
with the body after the last pattern), but in Haskell there is not.您可以使用
-XViewPatterns
添加任意函数,将两种情况折叠成单个模式。您的模式现在是一个函数
p
,它会生成您想要匹配的内容:简单得多!
不过,我们必须将
p
定义为:或者您希望在查看之前标准化数据。
参考资料GHC 用户指南中有关视图模式的章节
You can use
-XViewPatterns
, to add arbitrary functions to collapse your two cases into a single pattern.Your pattern is now a function
p
that yields the thing you want to match:much simpler!
We have to define
p
though, as:or however you wish to normalize the data before viewing.
References: The GHC User's Guide chapter on View Patterns