如何组合案例陈述模式

cro*_*eea 7 haskell ghc

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

case x of
  C1 -> foo x
  C2 -> foo x
  ...
  C10 -> bar x
  C11 -> bar x
  ...
Run Code Online (Sandbox Code Playgroud)

是否有一些方法可以使case语句的行为更像switchC中的语句(即通过fallthrough),或者我可以同时匹配多个模式中的一个,例如:

case x of
  C1, C2, C3 -> foo x
  C10, C11, C12 -> bar x
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*rdy 10

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

case cond of
  c
    | c `elem` [C1, C2, C3] -> foo
    | c `elem` [C10, C11, C12] -> bar
    | otherwise -> baz
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)