Explain the Phantom Type pattern in Haskell to implement a unit-safe physics library…
- User
Explain the
Phantom Typepattern in Haskell to implement a unit-safe physics library (prevent adding Meters to Seconds). Assistant
Explain the Phantom Type pattern in Haskell to implement a unit-safe physics library (prevent adding Meters to Seconds).
1. Understand the Goal: The user wants an explanation of the "Phantom Type" pattern in Haskell, specifically applied to creating a unit-safe physics library (preventing operations like Meters + Seconds).
Target Audience: Likely a Haskell learner or someone interested in type-level programming. The explanation needs to be clear, code-heavy, and demonstrate the value of the pattern (safety).
Core Concept - Phantom Types:
Application - Physics Library:
data Value unit = Value Double (The unit parameter is phantom).Meter, Second).Drafting the Code Structure:
Step 1: Defining the types.
data Meter
data Second
data Value u = Value Double
Step 2: Smart constructors. To create values easily.
meter :: Double -> Value Meter
meter = Value
Step 3: Arithmetic operations.
Value a + Value b = Value (a + b) (needs same u).Value a * Value b = Value (a * b) (changes u).Step 4: Advanced Units (Compound Units).
Just Meter and Second isn't enough. We need Meter / Second (Velocity) or Meter / Second^2 (Acceleration).
DataKinds and GADTs or type operators.:*: and :/: to show how types change during math.Structuring the Explanation:
Double is bad for physics (5.0 + 10.0 might be meters + seconds).data declaration.Quantity or Value).Num instance (crucial for +, *).Refining the Code (Self-Correction during drafting):
data Meter
data Value u = Value Double deriving Show
If I do (+) on Value, I need Value u -> Value u -> Value u. This is standard.
What about (*)? Value u1 -> Value u2 -> Value (u1 * u2). Haskell doesn't let you multiply types by default easily without extensions.
Correction: I should stick to addition/subtraction for the core explanation of Phantom Types to keep it accessible. Multiplying types involves Type Families, which might confuse the "Phantom Type" explanation specifically. I will explain multiplication as "transforming the phantom parameter" but maybe stick to simpler types for the example unless I use the units package approach or simple type families.
Better approach: Let's use Type Families for the math to make it a "real" physics library example, but explain it clearly. Or, simpler: just manually specify the resulting types for the example to focus on the Phantom aspect.Let's stick to a clean example using DataKinds and KindSignatures is the modern way, but standard ADTs are easier to explain. I will use empty data declarations.
Code Plan:
data Metersdata Secondsnewtype Quantity u = Quantity DoubleNum instance for Quantity.Wait, (*) implementation in Num:
(*) :: Quantity a -> Quantity b -> Quantity ???
Haskell's standard Num class expects * :: a -> a -> a. It cannot return a different type.
Crucial Point: Phantom types break the standard Num interface for * if the units change.
Workaround: Don't use Num for multiplication. Use custom operators like .+. or specific mult functions.
Actually: To keep the example simple and focused on the pattern, I will define custom operators like add and mult so I don't get bogged down in Type Families or RebindableSyntax.
Finalizing the Content Flow:
newtype Unit u = Unit Double.data Meter; data Second.add :: Unit a -> Unit a -> Unit a (Safe!)mult :: Unit a -> Unit b -> Unit (Mult a b) (Requires type families... maybe keep this out or add as an "Advanced" note? I'll include a simple type family example because physics requires it).Unit Meter erases to just Double in the compiled code.Writing the Response (Mental Draft):
newtype.u not on the right side).Meter / Second definitions.Refining the Multiplication Part:
If I do type family Mul a b where Mul Meter Meter = MeterSquared, that's cool.
I will present a basic version first (Distinct types, simple addition).
Then a "Level 2" version with Type Families for Multiplication to show the full power.
Polishing: Ensure GHC extensions are mentioned (DataKinds, GeneralizedNewtypeDeriving).
(Self-Correction during final output generation):
Make sure to emphasize why it's called "Phantom". Because the variable u disappears at runtime.
Let's write it out.
This looks solid. I will proceed with generating the response based on this structure. A Phantom Type is a parameterized type whose parameter is not used in the data constructors. In other words, the type variable exists only on the "left side" of the definition (the type signature) but not on the "right side" (the actual data structure).
In the context of a physics library, this allows us to use the Haskell compiler to enforce mathematical rules—specifically, that you cannot add a distance (Meters) to a time (Seconds).
Here is a step-by-step explanation and implementation.
Imagine we wrap a number in a data type. Usually, the type parameter determines what is inside:
-- 'a' appears on the right side, so it is NOT phantom
data Box a = Box a
If we make a disappear from the right side, it becomes a Phantom Type:
-- 'a' does NOT appear on the right side
newtype Unit a = Unit Double
Even though the Unit holds a Double, the type variable a acts as a "tag" or a "phantom" that follows the value around. This tag exists purely for the compiler to check logic at compile time; it is erased when the program actually runs (zero runtime overhead).
To make this work for physics, we need:
Here is the complete, runnable Haskell code:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
module Physics where
-- 1. The Wrapper
-- We use 'newtype' for zero runtime overhead.
-- The 'a' is the Phantom Type. It tags the Double.
newtype Value a = Value Double
deriving (Show, Eq)
-- 2. The "Tags" (Unit Definitions)
-- These data types have no constructors. They only exist in the type system.
data Meter
data Second
data Kilogram
-- 3. Smart Constructors
-- These helper functions make it easy to create values.
meters :: Double -> Value Meter
meters = Value
seconds :: Double -> Value Second
seconds = Value
-- 4. Unit-Safe Arithmetic
-- Notice how 'a' is the same in the input and output.
-- This prevents adding Meters to Seconds.
add :: Value a -> Value a -> Value a
add (Value x) (Value y) = Value (x + y)
-- Subtraction works similarly
sub :: Value a -> Value a -> Value a
sub (Value x) (Value y) = Value (x - y)
-- 5. Handling Compound Units (Type Algebra)
-- We need a way to represent Meters * Meters = Meters^2
-- or Meters / Second = Velocity.
-- We use Type Families to tell the compiler how types combine.
-- Define type level operators for Multiplication and Division
type family (*) a b
type family (/) a b
-- Define the rules for combining units
-- Meters * Meters = Square Meters
type instance Meter * Meter = SquareMeter
data SquareMeter
-- Meters / Seconds = Velocity
type instance Meter / Second = Velocity
data Velocity
-- Now we define the math operators that change the units
mult :: Value a -> Value b -> Value (a * b)
mult (Value x) (Value y) = Value (x * y)
div :: Value a -> Value b -> Value (a / b)
div (Value x) (Value y) = Value (x / y)
Now, let's see what happens when we try to write correct vs. incorrect code.
We calculate the area of a square (Side Side). Both are Meter. The compiler expects the result to be Meter * Meter.
width :: Value Meter
width = meters 10.0
length :: Value Meter
length = meters 5.0
-- This compiles successfully.
-- The result type is 'Value (Meter * Meter)' which resolves to 'Value SquareMeter'
area = width `mult` length
We try to add Meters to Seconds.
distance :: Value Meter
distance = meters 100
time :: Value Second
time = seconds 10
-- This will NOT compile!
-- The 'add' function expects: Value a -> Value a -> Value a
-- But we gave it: Value Meter -> Value Second
badCalculation = distance `add` time
Compiler Output:
Couldn't match type ‘Second’ with ‘Meter’ arising from a use of ‘add’
The compiler effectively caught a physics error: "You cannot add Meters to Seconds."
We divide distance by time. The compiler automatically infers the resulting type is Velocity.
dist :: Value Meter
dist = meters 100
t :: Value Second
t = seconds 20
-- The compiler infers: speed :: Value (Meter / Second)
-- which resolves to: speed :: Value Velocity
speed = dist `div` t
newtype Value a = Value Double. The a is phantom because it isn't stored in the Value.newtype and empty data types (no constructors), the compiler erases all the Meter, Second, and Value wrappers after type checking. The final compiled code is just raw Double arithmetic (just as fast as C).