How to combine case statement patterns [duplicate]

拈花ヽ惹草 提交于 2019-12-21 12:15:05

问题


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
  ...

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?


回答1:


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

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


来源:https://stackoverflow.com/questions/29246108/how-to-combine-case-statement-patterns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!