newtype and type synonyms

type is a synonym

type introduces another name for an existing type. It disappears during compilation, so the two names are fully interchangeable and neither is safer:

type Name = String type Phone = String -- legal and wrong: the compiler sees String -> String call :: Name -> Phone -> String call name phone = name ++ " " ++ phone

Synonyms are documentation for signatures. They make a [(String, Int)] readable, and they cost nothing at runtime.

newtype is a wrapper

newtype declares a type with exactly one constructor and one field. Unlike a synonym, the compiler keeps it distinct:

newtype Name = Name String newtype Phone = Phone String deriving (Show, Eq) -- now this is a type error, which is the point call :: Name -> Phone -> String call (Name n) (Phone p) = n ++ " " ++ p bad = call "Ada" "555-0100"

Newtype.hs:9:12: error: [GHC-83865] • Couldn’t match type ‘[Char]’ with ‘Name’ Expected: Name Actual: String • In the first argument of ‘call’, namely ‘"Ada"’ In the expression: call "Ada" "555-0100" In an equation for ‘bad’: bad = call "Ada" "555-0100" | 9 | bad = call "Ada" "555-0100" | ^^^^^ Newtype.hs:9:18: error: [GHC-83865] • Couldn’t match type ‘[Char]’ with ‘Phone’ Expected: Phone Actual: String • In the second argument of ‘call’, namely ‘"555-0100"’ In the expression: call "Ada" "555-0100" In an equation for ‘bad’: bad = call "Ada" "555-0100" | 9 | bad = call "Ada" "555-0100" | ^^^^^^^^^^

Passing a phone number where a name belongs no longer compiles. That class of bug is invisible in a language where both are strings.

Why wrap anything

A wrapper is the cheapest way to attach meaning and invariants. The constructor is the only way in, so validation happens once:

newtype Age = Age Int deriving (Show, Eq, Ord) mkAge :: Int -> Maybe Age mkAge n | n >= 0 && n < 150 = Just (Age n) | otherwise = Nothing

The type now means a validated age, not just any number. Functions that need a real age take Age and stop re-checking the range.

Zero cost

A newtype has no runtime representation of its own: the constructor is erased and the wrapped value is used directly. You get the type safety of a wrapper at the cost of the underlying type:

-- both compile to the same machine code plain :: Int -> Int plain n = n + 1 wrapped :: Age -> Age wrapped (Age n) = Age (n + 1)

That is why the standard library uses newtypes for Sum, Product, Any and All, which lesson 43 revisits.

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

Article author: Arthur Isaev