Let’s say I want to simplify my case analysis. PatternSynonyms
extension is perfect for it. I use COMPLETE
pragma to avoid the warning about incomplete case analysis and the code is:
{-# COMPLETE DInt #-}
data D = D1 Int | D2 Int | D3 String deriving (Eq, Show)
pattern DInt :: Int -> D
pattern DInt t <- (dInt -> Just t)
dInt :: D -> Maybe Int
dInt (D1 n) = Just n
dInt (D2 n) = Just n
dInt _ = Nothing
f1 :: D -> String
f1 d =
case d of
D3 s -> "str:" <> s
DInt n -> "num:" <> show n
It works OK, but if I write the case as:
case d of
DInt n -> ... -- without D3 branch !
then it leads to runtime exception without compile time warning! And the missing of warning is the problem 1.
Then, I try this:
case d of
DInt n -> "num:" <> show n
D3 s -> "str:" <> s -- WARNING
and it works fine, but I get a warning: “Pattern match is redundant”, and this is the problem 2.
How to fix/avoid these 2 problems? Maybe the synonym is written in the wrong way?
PS. Sure the example is kiddish in real app terms are large, cases too
PPS. The idea behind patterns like DInt
is to conclude (reduce) multiple different cases to one.
EDIT: Obvious solution is to move the conversion to string to the synonym, but in the real app I have a situation when some of terms/branches cannot lead to meaningful values, so – Nothing
is used.
1