Phantom types

A state in the type

A document has a stage: a draft can be published, and a published document cannot be published again. The usual encoding is a field with a value, which is a check at run time. A phantom parameter is the same state in the type, where the compiler checks it:

data Stage = Draft | Published newtype Doc (s :: Stage) = Doc String publish :: Doc 'Draft -> Doc 'Published

The constructor Doc stores a string and nothing else; the parameter s appears in the type of the value and in the types of the functions, and the promotions 'Draft and 'Published come from DataKinds. A function that publishes takes a draft and returns a published document, so the state travels with the value and no field can disagree with it.

Draft and Published

{-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} module Main (main) where data Stage = Draft | Published newtype Doc (s :: Stage) = Doc String draft :: Doc 'Draft draft = Doc "release notes" publish :: Doc 'Draft -> Doc 'Published publish (Doc text) = Doc text render :: Doc s -> String render (Doc text) = text main :: IO () main = do putStrLn (render draft) putStrLn (render (publish draft))

ghc -Wall -O1 -o phantom phantom.hs
./phantom

release notes
release notes

render works for any stage because it does not care about the parameter, and publish changes the stage in its type. Both calls print the same string, which is the point: the state is not data and it does not show. It exists only while the compiler is checking, and the run-time value is the string alone.

Publishing twice

The second call is rejected because the result of the first is a Doc 'Published and publish wants a Doc 'Draft:

{-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} module Main (main) where data Stage = Draft | Published newtype Doc (s :: Stage) = Doc String publish :: Doc 'Draft -> Doc 'Published publish (Doc text) = Doc text main :: IO () main = putStrLn (render (publish (publish (Doc "x")))) render :: Doc s -> String render (Doc text) = text

ghc -Wall -fno-code twice.hs

twice.hs:14:35: error: [GHC-83865]
    • Couldn't match type ‘Published’ with ‘Draft’
      Expected: Doc Draft
        Actual: Doc Published
    • In the first argument of ‘publish’, namely ‘(publish (Doc "x"))’
      In the first argument of ‘render’, namely
        '(publish (publish (Doc "x")))'
      In the first argument of ‘putStrLn’, namely
        '(render (publish (publish (Doc "x"))))'
  |
14 | main = putStrLn (render (publish (publish (Doc "x"))))
   |                                  ^^^^^^^^^^

The error is at the inner call, where the result of publishing is handed to publishing again. With a stage field the same program would compile and fail at run time, or need a check that returns a Maybe; here the illegal state has no value, so there is no run-time error to write.

Where the state belongs

The parameter is worth it when the state has a small set of values and the transitions are few. It is a cost when the program has to store the state to show it, or when a value has to be read from a file and the stage comes with it: a database row has a stage column, and the boundary converts the column into the type once.

The next lesson leaves the type system and calls C: the FFI is how a Haskell program reaches a library that was written for another language.

Exercises

  1. Add a review :: Doc 'Published -> Doc 'Draft and use it.
  2. Add an Archived stage and an archive :: Doc 'Published -> Doc 'Archived.
  3. Write the same program with a stage field and a check that returns Maybe, and compare the call sites.
  4. Explain why render :: Doc s -> String works for every stage.
  5. Add a Show instance for Doc s that prints the text and say what it cannot print.
  6. Decide for three programs (a blog, a spreadsheet cell, a network packet) whether a phantom stage is worth it.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is a phantom type parameter?

    Answer

    A parameter that appears only in the type and stores no value

    Doc s stores only the String; s exists for the checker.

  2. What does publish :: Doc 'Draft -> Doc 'Published change?

    Answer

    The stage in the type, with the same string inside

    The function returns a value of a different type with the same content.

  3. Why does publishing twice fail to compile?

    Answer

    The second publish needs a Draft and gets a Published

    The state travelled with the value, so the second call has the wrong type.

  4. What does this program print? {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} module Main (main) where data Stage = Draft | Published newtype Doc (s :: Stage) = Doc String main :: IO () main = putStrLn (case Doc "hi" of Doc text -> text)

    Answer

    hi

    The case takes the text out of the newtype and putStrLn prints it.

  5. What does the phantom parameter cost at run time?

    Answer

    Nothing

    The parameter is erased, so the representation is the String alone.

  6. What does this program print? module Main (main) where newtype Tagged t a = Tagged a main :: IO () main = print (case Tagged (3 :: Int) of Tagged n -> n + 1)

    Answer

    4

    The case returns the Int and the expression adds one.

  7. When is a phantom parameter a poor choice?

    Answer

    When the state comes from outside and must be stored or printed

    A database row or a user input carries the state as data, and the type cannot enumerate it.

  8. What does this program print? module Main (main) where newtype Doc = Doc String main :: IO () main = putStrLn (case Doc "x" of Doc t -> t ++ t)

    Answer

    xx

    The text is doubled by ++ before putStrLn prints it.

  9. Why can render :: Doc s -> String ignore the parameter?

    Answer

    It never needs to know the stage, only the text

    A function polymorphic in s works for every stage, which is the point of the parameter being free.

  10. Which two pragmas does this lesson use?

    Answer

    DataKinds and KindSignatures

    DataKinds promotes Draft and Published, and KindSignatures writes (s :: Stage).

The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image