Haskell Type Synonyms & newtype
Besides data, Haskell has two more ways to name types: type creates an alias, another name for an existing type, and newtype creates a genuinely new type with zero runtime cost. They look similar but serve opposite purposes: one is for readability, the other for safety.
type: an alias for readability
type Name = String
type Price = Double
type Basket = [(Name, Price)]
basketTotal :: Basket -> Price
basketTotal items = sum (map snd items)
cheapest :: Basket -> Name
cheapest items = fst (foldr1 (\a b -> if snd a <= snd b then a else b) items)
main :: IO ()
main = do
let basket = [("bread", 2.2), ("cheese", 5.75), ("olives", 3.1)]
print (basketTotal basket)
putStrLn (cheapest basket)
print (length ("plain string" :: Name))11.05
bread
12
Basket -> Price reads much better than [(String, Double)] -> Double. But a synonym is only a new name. Name and String are completely interchangeable, and so are Price and any other Double. String itself is the synonym type String = [Char].
Synonyms can take parameters too:
type Pair a = (a, a)
type Lookup k v = [(k, v)]
swapPair :: Pair a -> Pair a
swapPair (x, y) = (y, x)The problem synonyms don't solve
Suppose some functions work with metres and others with feet. Synonyms document that, but they don't stop you from mixing them up:
type Metres = Double
type Feet = Double
runwayLength :: Metres
runwayLength = 3000
requiredFeet :: Feet
requiredFeet = 9000
main :: IO ()
main = print (runwayLength > requiredFeet) -- compiles, but compares metres with feet!False
The answer is wrong (3000 m is about 9843 ft, so the runway is long enough), and the compiler couldn't help, because both are plain Double.
newtype: a distinct type
A newtype declaration wraps exactly one existing type in a new constructor. The compiler now treats it as a different type, so mixing units is a type error:
newtype Metres = Metres Double deriving (Show, Eq, Ord)
newtype Feet = Feet Double deriving (Show, Eq, Ord)
toFeet :: Metres -> Feet
toFeet (Metres m) = Feet (m * 3.28084)
runwayLength :: Metres
runwayLength = Metres 3000
requiredLength :: Feet
requiredLength = Feet 9000
main :: IO ()
main = do
print (toFeet runwayLength)
print (toFeet runwayLength > requiredLength)Feet 9842.52
True
Now runwayLength > requiredLength would not compile: you must convert explicitly. At run time a newtype costs nothing: the wrapper exists only during type checking, and the compiled program works on the raw Double.
Accessing the wrapped value
The usual way is a record field, by convention named unSomething or getSomething:
newtype UserId = UserId {unUserId :: Int} deriving (Show, Eq, Ord)
newtype Email = Email {getEmail :: String} deriving Show
mkEmail :: String -> Maybe Email
mkEmail s
| '@' `elem` s && '.' `elem` dropWhile (/= '@') s = Just (Email s)
| otherwise = Nothing
main :: IO ()
main = do
let uid = UserId 42
print uid
print (unUserId uid + 1)
print (mkEmail "ada@example.org")
print (mkEmail "not-an-email")
print (fmap getEmail (mkEmail "bob@test.io"))UserId {unUserId = 42}
43
Just (Email {getEmail = "ada@example.org"})
Nothing
Just "bob@test.io"
mkEmail is a smart constructor: if a module exports Email and mkEmail but not the Email constructor, the only way to obtain an Email is through the check. Every Email in the program is then known to be valid.
newtype and type classes
Because a newtype is a new type, it can have its own instances, different from the wrapped type's. This is how one type can be combined in several ways (summing or multiplying numbers, for instance), which you will meet in the Semigroup & Monoid lesson:
newtype Celsius = Celsius Double
instance Show Celsius where
show (Celsius c) = show c ++ " C"
main :: IO ()
main = do
print (Celsius 21.5)
print [Celsius 0, Celsius 100]21.5 C
[0.0 C,100.0 C]
data, type or newtype?
| Declaration | Creates | Constructors | Runtime cost | Use for |
|---|---|---|---|---|
type T = … |
an alias | none | none | shorter, more descriptive signatures |
newtype T = C X |
a new, distinct type | exactly one, with exactly one field | none | units, IDs, validated values, alternative instances |
data T = … |
a new type | any number, any fields | small (a box per value) | everything else |
Note: A newtype is also slightly lazier in pattern matching than a one-field
datatype, because matching on it doesn't evaluate anything. In practice you choosenewtypewhenever you wrap a single value.
Test yourself
After type Age = Int, can you pass an Int where an Age is expected?
- No, it is a type error
- Yes, a synonym is just another name for the same type
- Only with a conversion function
- Only in GHCi
Which declaration is valid?
newtype Pair = Pair Int Intnewtype Id = Id Int | NoIdnewtype Id = Id Intnewtype Id
What is the runtime cost of a newtype wrapper?
- One extra pointer per value
- None: it is erased after type checking
- A copy of the value
- It depends on the field type