Patterns and View patterns: am I doing this right

104 views Asked by At

I want to achieve

{-# LANGUAGE PatternSynonyms, ViewPatterns    #-}

pattern Just2 :: (Num a, Eq a) => a -> a -> Maybe (a, a)

-- Just2 0 0 ≡ Nothing
-- Just2 x y ≡ Just (x, y)

I think I've got there via a View pattern, but the code seems verbose. Is there a more elegant way?

pattern Just2 x y <- (fromMaybe2 -> (x, y))  where
  Just2 0 0 = Nothing
  Just2 x y = Just (x, y)

fromMaybe2 Nothing       = (0, 0)
fromMaybe2 (Just (x, y)) = (x, y)

-- examples

foo (Just2 x y) = x + y

z0  = Nothing
z2  = Just (7, 8)
z00 = Just (0, 0)

*Main> foo z0
0
*Main> foo z2
15
*Main> foo z00
0

-- here's an oddity

*Main> (\ z@(Just2 x y) -> z) Nothing                -- round trip - as expected
Nothing

*Main> (\ z@(Just2 x y) -> Just2 x y) $ Just (0, 0)  -- not a round trip - as expected
Nothing
*Main> (\ z@(Just2 x y) -> z) $ Just (0, 0)          -- round trip - not as expected
Just (0,0)

Addit: Thanks @chi. I feel very tempted to write

pattern { Just2 0 0 = Nothing;
          Just2 x y = Just (x, y)
        }

With the idea the compiler treats those equations as defining a pair of functions, reading from l to r or r to l depending on what it wants, and reading top to bottom to pattern-match.

0

There are 0 answers