如何合并案例陈述模式 [英] How to combine case statement patterns

查看:66
本文介绍了如何合并案例陈述模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在case语句中匹配许多不同的构造函数.为简单起见,假设一半情况下我们做同样的事情,另一半情况下我们做其他事情.即使我将逻辑分解为另一个函数,我仍然必须编写:

I'm trying to match on many different constructors in a case statement. For simplicity, assume in half the cases we do the same thing, and in the other half we do something else. Even if I factor out the logic to another function, I still have to write:

case x of
  C1 -> foo x
  C2 -> foo x
  ...
  C10 -> bar x
  C11 -> bar x
  ...

有没有办法使case语句的行为更像C中的switch语句(即具有穿透),或者使我可以一次匹配多个模式之一,例如:

Is there some way to make case statements behave more like switch statements in C (i.e. with fallthrough), or so that I can match on one of many patterns at once, like:

case x of
  C1, C2, C3 -> foo x
  C10, C11, C12 -> bar x

或者也许是另一种清理方法?

Or perhaps another way to clean this up?

推荐答案

这些称为析取模式,而Haskell没有. (OCaml和F#可以.)但是,有一些典型的解决方法.如果您的类型是枚举,则可以使用等号,例如elem:

These are called disjunctive patterns, and Haskell does not have them. (OCaml and F# do.) There are a few typical workarounds, however. If your type is an enumeration, you can use equality, with for example elem:

case cond of
  c
    | c `elem` [C1, C2, C3] -> foo
    | c `elem` [C10, C11, C12] -> bar
    | otherwise -> baz

当然,如果foobar是长表达式,由于懒惰,您可以将它们简单地分解为局部定义,因此您只需重复名称和需要用作参数的任何模式变量:

And of course, if foo or bar are long expressions, thanks to laziness you can simply factor them into local definitions, so you only have to repeat the name and any pattern variables you need as arguments:

case cond of
  C1 x -> foo x
  C2 y -> foo y
  ...
  C10 -> bar
  C11 -> bar
  ...
where
foo x = something long (involving x, presumably)
bar = if you please then something else quite long

这篇关于如何合并案例陈述模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆