Haskell Type Inference
You have been writing type signatures, but GHC does not actually need most of them. It infers the type of every expression by looking at how values are used. This lesson shows how inference works, when you still need annotations, and why writing top-level signatures is good practice anyway.
Leaving out the signature
-- No signatures at all: GHC works out the types itself.
double x = x * 2
greeting name = "Hi, " ++ name
both p q = p && q
main = do
print (double 21)
print (double 1.5)
putStrLn (greeting "Linus")
print (both True False)42
3.0
Hi, Linus
False
How did GHC decide?
greetinguses++with a string literal, sonamemust be aStringand so is the result:greeting :: String -> String.bothuses&&, which only works onBool:both :: Bool -> Bool -> Bool.doubleuses*, which works for any numeric type. GHC infers the most general type,double :: Num a => a -> a, which is why it accepted both21and1.5.
That last type has a constraint (Num a =>): "for any type a that is a number". Constraints come from type classes, which have their own lesson.
Inspecting inferred types in GHCi
In GHCi, :type shows what GHC inferred:
ghci> double x = x * 2
ghci> :type double
double :: Num a => a -> a
ghci> :type "abc" ++ "d"
"abc" ++ "d" :: [Char]
ghci> :type (\x -> x)
(\x -> x) :: p -> p
ghci> :type length
length :: Foldable t => t a -> IntTip: When you are not sure what to write in a signature, define the function without one, ask GHCi with
:t, and paste the answer into your file. Language servers (HLS) offer the same thing as a one-click "add signature" action.
Defaulting: what type is 42?
A number literal like 42 is polymorphic: it can be an Int, an Integer, a Double and so on. When nothing forces a choice, GHC defaults to Integer for whole numbers and Double for decimals:
main :: IO ()
main = do
print (2 ^ 80) -- defaults to Integer: no overflow
print (2 ^ 80 :: Int) -- forced to Int: wraps to 0
print (7 / 2) -- defaults to Double
print (fromIntegral (length "hello") / 2)1208925819614629174706176
0
3.5
2.5
length always returns an Int, and / needs a fractional type, so fromIntegral converts the Int into whatever numeric type the surroundings require (here, Double).
When inference needs help
Sometimes the code doesn't contain enough information. read turns a string into a value, but into which type?
main :: IO ()
main = do
let n = read "42" :: Int
x = read "2.5" :: Double
xs = read "[1,2,3]" :: [Int]
print (n + 1)
print (x * 2)
print (sum xs)43
5.0
6
The annotations :: Int, :: Double and :: [Int] pick the type. Often you do not even need them, because the use site decides: in read s + length xs, the result must be an Int. Without any clue, GHC complains that the type is ambiguous:
main :: IO ()
main = putStrLn (show (read "42"))GHC rejects this program. The message is long because it lists candidate types, but it starts like this:
<source>:2:18: error: [GHC-39999]
* Ambiguous type variable `a0' arising from a use of `show'
prevents the constraint `(Show a0)' from being solved.
Probable fix: use a type annotation to specify what `a0' should be.GHC even suggests the fix: "use a type annotation".
Why still write signatures?
If GHC can infer everything, why does idiomatic Haskell put a signature on every top-level function?
- Documentation.
parsePrice :: String -> Maybe Doubletells a reader more than the implementation does. - Better error messages. Without a signature, a mistake inside the function may be reported far away, where the wrongly inferred type finally clashes with a use.
- Intent over accident. The inferred type may be more general (or more specific) than you meant. A signature pins down the design.
This example shows point 3. Without a signature, average would get a very general type; with one, it is restricted to what we want:
average :: [Double] -> Double
average xs = sum xs / fromIntegral (length xs)
main :: IO ()
main = do
print (average [2, 4, 9])
print (average [1.5, 2.5])5.0
2.0
Note: Local helpers inside
whereandletusually don't get signatures; top-level definitions do. GHC's-Wallwarning set even warns about top-level definitions without one.
Test yourself
What type does GHC infer for double x = x * 2?
Int -> IntDouble -> DoubleNum a => a -> aa -> a
Why is show (read "42") rejected?
readcannot parse numbers- The type to read into is ambiguous
showneeds two arguments- Strings cannot be shown
With no other information, what type does the literal 2.5 default to?
FloatDoubleRationalInteger