Home > OS >  Pattern synonym with "virtual" arg and conjunction
Pattern synonym with "virtual" arg and conjunction

Time:11-30

Let's say I have types:

data Some a = S1 a | S2 a

data BigRec = BigRec {
  some :: Some [Int]
  , ...
  }

and I want a pattern synonym that will have a "virtual argument", like

pattern BadBigRec t <- ...

where t is True or False which depends on the value of some: if it's S1 something-particular - it's True, else if it is S2 something-other, it's False. I hit 2 problems: I don't know how to have an "argument" in a pattern synonym which is only in the left hand side and it is not presented in the right hand side (t is "virtual" and it does not exist in BigRec or Some). And the second problem, I don't know how to express "OR" (conjunction) in pattern synonyms. Not just pattern that match, but a conjunct of predicates.

Is it possible with pattern synonyms or only pattern views are useful for such cases?

CodePudding user response:

As mentioned in the comments, you can use a view pattern.

{-# LANGUAGE ViewPatterns, PatternSynonyms #-}

data Some a = S1 a | S2 a

data BigRec = BigRec {
  some :: Some [Int]
  }

pattern BadBigRec :: Bool -> BigRec
pattern BadBigRec t <- (checkBad -> t)

-- modify this as needed
checkBad :: BigRec -> Bool
checkBad x = case some x of
   S1 _ -> True
   S2 _ -> False
  • Related