Or-patterns in Haskell

此生再无相见时 提交于 2019-12-21 03:13:35

问题


In OCaml, I was used to writing code which looked like:

let combine o1 o2 = match o1, o2 with
    | Valid, Invalid | Invalid, Valid -> Invalid
    | _ -> ...

I didn't find a way to write or-patterns in Haskell and I really miss it. Does anyone have a solution?


回答1:


I don't think this is possible in haskell. There are however, a few alternatives:

Factor out the common code with a where binding

This doesn't make much sense in your example, but is useful if you have more code in the body of the case expression:

combine o1 o2 = case (o1,o2) of
  (Valid, Invalid) -> handleInvalid
  (Invalid, Valid) -> handleInvalid
  ...
 where
  handleInvalid = ...

Use wildcard patterns

In my experience, it doesn't happen so often that you want to use two or patterns in one pattern match. In this case, you can handle all the "good" cases and the use a wild card pattern for the rest:

combine o1 o2 = case (o1,o2) of
  (Valid, Valid) -> Valid -- This is the only valid case
  _              -> Invalid -- All other cases are invalid

This has the disadvantage that it bypasses the exhaustiveness checker and that you cannot use wildcard patterns for other purposes.

Use guards and ==

If the types you want to match against are enum-like types, you might consider making an Eq instance. Then you can use == and || to match multiple constructors in one guard:

combine o1 o2
  | o1 == Invalid && o2 == Valid || o1 == Valid && o2 == Invalid = Invalid
  | ...

I agree that this doesn't look as nice and it also has the disadvantage of bypassing the exhaustiveness checker and doesn't warn you if patterns overlap, so I wouldn't recommend it.




回答2:


You could use this quasiquoter http://hackage.haskell.org/package/OrPatterns. Your example translates to something like:

let combine o1 o2 = case (o1, o2) of
      [o| (Valid, Invalid) | (Invalid, Valid ) |] -> Invalid
      _ -> ...



回答3:


There is a proposal to add or-patterns to GHC.

Until then (in addition to the other examples), pattern synonyms can be employed for similar means:

data ABC = A Int | B Int | C Bool

ab :: ABC -> Maybe Int
ab (A i) = Just i
ab (B i) = Just i
ab C{}   = Nothing

pattern AB :: Int -> ABC
pattern AB i <- (ab -> Just i)

If you want to match values of separate types (like Int and Bool) you can create some constrained existential type

data Showable where
  Showable :: Show a => a -> Showable

ac :: ABC -> Maybe Showable
ac (A i) = Just (Showable i)
ac (C b) = Just (Showable b)
ac B{}   = Nothing

pattern AC :: () => Show a => a -> ABC
pattern AC showable <- (ac -> Just (Showable showable))

showAC :: ABC -> String
showAC (AC showable) = "A or C: " ++ show showable
showAC (B i)         = "B: "      ++ show i


来源:https://stackoverflow.com/questions/24700762/or-patterns-in-haskell

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