haskellphantom-types

Phantom type confusion?


I'm confused over the use of phantom types:

type Words = String
type Numbers = Int

data NonPhantom = NP1 Words | NP2 Numbers deriving (Show)

data Phantom a = P1 Words | P2 Numbers deriving (Show) 

nonPhantomFunction :: NonPhantom -> Int
nonPhantomFunction r = 100


phantomFunction :: Phantom Numbers -> Int
phantomFunction a = 2001


main = do
   print $ nonPhantomFunction (NP1 "sdsdds") --can also pass NP2 here! 
   print $ phantomFunction (P1 "sdsdsd") --This shouldn't work!?

I expect this code NOT to compile, as the phantomFunction explicitly states its expecting data type Phantom of Numbers.

However this compiles fine? What am I doing wrong?


Solution

  • data Phantom a = P1 Words | P2 Numbers deriving (Show) 
    

    This makes P1 "aa" of any type of the form Phantom a, for any a, including Numbers.