3 ms·
Phantom types are used frequently in Haskell to really great effect. Perhaps the most well-known example is the ST monad which allows you to do mutable, destruc
by tel 13y ago
Phantom types are used frequently in Haskell to really great effect. Perhaps the most well-known example is the ST monad which allows you to do mutable, destructive updates in a "pure" fashion by containing them all within a narrow region. From outside of that region, the effects are invisible and referentially transparent. This is great for embedding your favorite iterative/mutable algorithm in a pure program.
Phantom types along with quantified type erasure allow the compiler to force these impure regions to be contained. They disallow sharing of variables or results between ST monad invocations statically.
To do so, most operations are polymorphic in the phantom variable. So something like `get (put x box)` is of type `ST s Int` for an `x :: Int`. The `s` corresponds to whichever ST region this action gets run within.
Running ST looks like `runST :: (forall s. ST s a) -> a` which means that the ST action you give to ST must be completely naive in its choice of region. Another way of thinking about it is that the `s` parameter is chosen adversarially by the compiler so that only ST actions which are able to be run in any region are allowed to be run at all.