TExcelTAD
Home › Haskell › Haskell Type Inference

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

haskell · try it yourself
-- 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?

  • greeting uses ++ with a string literal, so name must be a String and so is the result: greeting :: String -> String.
  • both uses &&, which only works on Bool: both :: Bool -> Bool -> Bool.
  • double uses *, which works for any numeric type. GHC infers the most general type, double :: Num a => a -> a, which is why it accepted both 21 and 1.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:

text
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 -> Int

Tip: 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:

haskell · try it yourself
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?

haskell · try it yourself
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:

haskell
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:

text
<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?

  1. Documentation. parsePrice :: String -> Maybe Double tells a reader more than the implementation does.
  2. 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.
  3. 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:

haskell · try it yourself
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 where and let usually don't get signatures; top-level definitions do. GHC's -Wall warning set even warns about top-level definitions without one.

Test yourself

What type does GHC infer for double x = x * 2?

  1. Int -> Int
  2. Double -> Double
  3. Num a => a -> a
  4. a -> a

Why is show (read "42") rejected?

  1. read cannot parse numbers
  2. The type to read into is ambiguous
  3. show needs two arguments
  4. Strings cannot be shown

With no other information, what type does the literal 2.5 default to?

  1. Float
  2. Double
  3. Rational
  4. Integer