Skip to content

Allow visible type application with pattern synonyms in patterns

Somewhat related to #13158 (closed), it would be nice if pattern synonyms allowed visible type application with the TypeApplications extension enabled. This would obviously be tricky due to the existing meaning of @ in patterns, though I think it would technically be unambiguous here. Still, I’d understand if you didn’t want to complicate the parser that much further.

The motivator, though, is that it would be nice to be able to write pattern synonyms with ambiguous types an explicitly instantiate them, for the same reason type applications are useful for terms. As mentioned in #13158 (closed), this would permit writing a pattern synonym to emulate case analysis on types:

{-# LANGUAGE GADTs, PatternSynonyms, ScopedTypeVariables,
             TypeApplications, TypeOperators, ViewPatterns #-}

import Data.Typeable

viewEqT :: forall b a. (Typeable a, Typeable b) => a -> Maybe ((a :~: b), b)
viewEqT x = case eqT @a @b of
  Just Refl -> Just (Refl, x)
  Nothing -> Nothing

pattern EqT :: forall b a. (Typeable a, Typeable b) => (a ~ b) => b -> a
pattern EqT x <- (viewEqT @b -> Just (Refl, x))

If visible type applications were permitted in patterns, then such case analysis could be written like this:

evilId :: Typeable a => a -> a
evilId (EqT @Int n) = n + 1
evilId (EqT @String str) = reverse str
evilId x = x

…which I think looks relatively pleasant!

Trac metadata
Trac field Value
Version 8.0.1
Type FeatureRequest
TypeOfFailure OtherFailure
Priority normal
Resolution Unresolved
Component Compiler
Test case
Differential revisions
BlockedBy
Related #13158 (closed)
Blocking
CC
Operating system
Architecture
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information