Phantom Type
Phantom types are type parameters that appear in a type's definition but not in its value constructors. They are used to encode additional static information at the type level without affecting runtime representation. This technique is common in Haskell for enforcing invariants, such as distinguishing between different kinds of data (e.g., meters vs. feet) or tracking state transitions (e.g., open vs. closed files), all with zero runtime overhead.
背景メモ
型システムの文脈における「幻の型(Phantom Type)」とは、型パラメータとして宣言されているものの、実際の値としては一切使われない型引数を指す。Haskellなどの強い静的型付け言語で、コンパイル時に追加の制約を表現するために使われる。
- 典型的な例:長さの単位(メートル、フィート)を型としてタグ付けし、異なる単位の値を誤って加算するようなバグをコンパイル時に防ぐ
- 値としては何のデータも持たないが、型としては区別されるため、実行時のオーバーヘッドなしに型安全を実現できる
- Data.VectorやDBアクセスライブラリなど、Haskellの現実のライブラリでも広く使われているパターン
- 他の言語(Rust、Scala、TypeScriptのブランド型など)にも同様の概念が存在する