Search code examples
haskellpattern-matchingtype-parameter

How do I specify type parameter in pattern matching for phantom type


Let's say I have this:

data PT1
data PT2
data DT1 a = DT1 { field :: Int }

newtype DT2 a = DT2 (DT1 a)

f :: Int -> DT2 a -> Int
f x (DT2 (DT1 PT1 field)) = 5 -- How do I specify the type param?
f x (DT2 (DT1 PT2 field)) = 7 -- How do I specify the type param?

The question is there in comments. The above doesn't compile. I want to pattern match differently based on the type parameter. How do I do so?


Solution

  • You can't pattern match on the type. What you can do is use a typeclass like this:

    class Effable t where
      f :: Int -> t -> Int
    
    instance Effable (DT2 PT1) where
      f x (DT2 _) = 5
    
    instance Effable (DT2 PT2) where
      f x (DT2 _) = 7