Phantom type
Overview
A phantom type is a parametrised type whose parameters do not all appear on the right-hand side of its definition
code:phantom.hs
newtype Const a b = Const { getConst :: a }
Here Const is a phantom type, because the b parameter doesn't appear after the = sign.
The motivation behind using phantom types is to specialize the return type of data constructors.
Phantom type can be used for Smart constructors or GADTs that encodes information about how and where a value can be used
Example code
Using #DataKinds
code:phantom.hs
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
data LengthUnit = Kilometer | Mile
newtype Distance (a :: LengthUnit) = Distance Double
deriving (Num, Show)
marathonDistance :: Distance 'Kilometer
marathonDistance = Distance 42.195
distanceKmToMiles :: Distance 'Kilometer -> Distance 'Mile
distanceKmToMiles (Distance km) = Distance (0.621371 * km)
marathonDistanceInMiles :: Distance 'Mile
marathonDistanceInMiles = distanceKmToMiles marathonDistance
Using GADT
code:gadtphantom.hs
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE StandaloneDeriving #-}
data Kilometer
data Mile
data Distance a where
KilometerDistance :: Double -> Distance Kilometer
MileDistance :: Double -> Distance Mile
deriving instance Show (Distance a)
marathonDistance :: Distance Kilometer
marathonDistance = KilometerDistance 42.195
distanceKmToMiles :: Distance Kilometer -> Distance Mile
distanceKmToMiles (KilometerDistance km) = MileDistance (0.621371 * km)
marathonDistanceInMiles :: Distance Mile
marathonDistanceInMiles = distanceKmToMiles marathonDistance
https://gyazo.com/174a87cb331cd69d5adf874500764dbb
Useful links
Haskellwiki
Motivation behind Phantom Types?
https://www.youtube.com/watch?v=cyOvlaweUtw
#Type_level_programming