Haskell/Phantom types

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Phantom types are a way to embed a language with a stronger type system than Haskell's.

Phantom types[edit | edit source]

An ordinary type

data T = TI Int | TS String

plus :: T -> T -> T
concat :: T -> T -> T

its phantom type version

data T a = TI Int | TS String

Nothing's changed - just a new argument a that we don't touch. But magic!

plus :: T Int -> T Int -> T Int
concat :: T String -> T String -> T String

Now we can enforce a little bit more!

This is useful if you want to increase the type-safety of your code, but not impose additional runtime overhead:

-- Peano numbers at the type level.
data Zero = Zero
data Succ a = Succ a
-- Example: 3 can be modeled as the type
-- Succ (Succ (Succ Zero)))

type D2 = Succ (Succ Zero)
type D3 = Succ (Succ (Succ Zero))

data Vector n a = Vector [a] deriving (Eq, Show)

vector2d :: Vector D2 Int
vector2d = Vector [1,2]

vector3d :: Vector D3 Int
vector3d = Vector [1,2,3]

-- vector2d == vector3d raises a type error
-- at compile-time:

--   Couldn't match expected type `Zero'
--               with actual type `Succ Zero'
--   Expected type: Vector D2 Int
--     Actual type: Vector D3 Int
--   In the second argument of `(==)', namely `vector3d'
--   In the expression: vector2d == vector3d

-- while vector2d == Vector [1,2,3] works