Types and type signatures
Every expression has a type
In Haskell a type is not an annotation you add for the compiler; it is a property every expression already has, and the compiler works it out before anything runs. Ask the shell:
GHCi, version 9.10.3: https://www.haskell.org/ghc/ :? for help
ghci> :type 1
1 :: Num a => a
ghci> :type 1.5
1.5 :: Fractional a => a
ghci> :type "abc"
"abc" :: String
ghci> :type 'a'
'a' :: Char
ghci> :type 1 + 2
1 + 2 :: Num a => a
ghci> :type length
length :: Foldable t => t a -> Int
ghci> :quit
Leaving GHCi.
The first four answers are worth reading twice. The literal
1 is not an Int: it is a
value of any type that has a Num instance, and the
type becomes concrete only where it is used. The literal
1.5 needs a fractional type, which is a smaller
group. A double-quoted string is a String, and a
single-quoted character is a Char: they are different
types, and the quotes are part of the difference.
The last answer explains why length works on a list,
on a Maybe and on a tree: its argument is
t a, where t is any
Foldable. Nothing in the definition mentions a list.
What the compiler infers
The type of a function is worked out from its definition, from the types of the functions it calls, and from the way its arguments are used. This definition never mentions a type:
add a b = a + b
and the compiler infers
add :: Num a => a -> a -> a. It knows the
result of (+) has the same type as its arguments,
that both arguments must have the same type, and that the type needs a
Num instance. That is genuinely more general than
Int -> Int -> Int, and it is why inference is
useful: the definition is written once and works for every numeric type.
It also means inference can produce a type you did not intend. A function
that looks like it works on integers may be inferred as
Integer because of one literal, or as
Double because of one division. The signature is how
you say which one you meant, and with -Wall the
compiler asks for it on every top-level binding.
Writing the signature down
A signature has the name, ::, and the type. Two arrows mean two arguments; the last type is the result. The file below has four definitions and four signatures, and two of the signatures are polymorphic:
module Main (main) where
firstOr :: a -> [a] -> a
firstOr fallback [] = fallback
firstOr _ (x : _) = x
main :: IO ()
main = do
print (firstOr (0 :: Int) [])
print (firstOr (0 :: Int) [7, 8])
putStrLn (firstOr "none" ["one", "two"])
print (length ([1, 2, 3] :: [Int]))
ghc -Wall -O1 -o signatures Signatures.hs
./signatures
[1 of 2] Compiling Main ( Signatures.hs, Signatures.o )
[2 of 2] Linking signatures
0
7
one
3
firstOr returns the first element of a non-empty list, and a fallback for the empty one. It does that for Int three lines down and for String four lines down, without a second definition: one function, two types, because the type is a variable.
Lowercase types are variables
A name that starts with a capital letter is a concrete type,
Int, Bool,
String. A name in lowercase is a type variable: it can
stand for any type, and every occurrence of the same name in one signature
must stand for the same type.
In a -> [a] -> a that rule does all the work.
The fallback is an a, the list is a list of
a, and the result is an a, so
a call with a String fallback needs a list of strings
and gives back a string. A call that mixes the two is a type error, which is
exactly the guarantee the caller wants.
The names mean nothing: a -> [a] -> a and
x -> [x] -> x are the same type. By convention
the first is a, the second b,
and so on; a name with a prime, a', is a different
variable.
The arrow with a constraint
A type variable can be restricted to the types that have an instance of a class. That is what => says:
double :: Num a => a -> a
double x = x + x
Read it as: for every type a that is a
Num, double takes an
a and returns an a. The part
before => is a promise the caller has to keep, not
a value the function receives; the compiler passes the right implementation
of (+) at the call site.
Constraints are how the standard library stays general without giving up
type safety: sort needs Ord,
show needs Show,
read needs Read. The
lesson on type classes
writes one of these classes from scratch.
String is [Char]
String is not a primitive type. It is a synonym for a list of characters, and the compiler says so:
ghci> :info String
type String :: *
type String = [Char]
-- Defined in ‘GHC.Internal.Base’
Everything that works on a list works on a string:
length "abcd" is 4, ++
concatenates two lists of characters, map toUpper
turns every character into an upper-case one, and a pattern
(x : _) takes the first character. In the program
above, firstOr "none" ["one", "two"] is a list of
strings, and firstOr 'a' "abc" would be a list of
characters.
This design is old and simple, and it is also why a large text-processing
program should reach for Data.Text or
ByteString later: a list of characters has a boxed
cell per character. The
lesson on Text measures the
difference.
A signature that lies
Because the signature is checked against the definition and against every call, a wrong one is caught. Here firstOr is given the type of a function that works only on numbers, and then called with a string:
module Main (main) where
firstOr :: Int -> [Int] -> Int
firstOr fallback [] = fallback
firstOr _ (x : _) = x
main :: IO ()
main = putStrLn (firstOr "none" ["one", "two"])
ghc -Wall -O1 -o wrong Wrong.hs
echo "status: $?"
[1 of 2] Compiling Main ( Wrong.hs, Wrong.o )
Wrong.hs:8:18: error: [GHC-83865]
• Couldn't match type ‘Int’ with ‘[Char]’
Expected: String
Actual: Int
• In the first argument of ‘putStrLn’, namely
‘(firstOr "none" ["one", "two"])’
In the expression: putStrLn (firstOr "none" ["one", "two"])
In an equation for ‘main’:
main = putStrLn (firstOr "none" ["one", "two"])
|
8 | main = putStrLn (firstOr "none" ["one", "two"])
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
status: 1
Three more errors follow it, one per argument, because the compiler reports
the call it cannot fit and then the arguments it could not match either. The
first is the one to read: putStrLn wants a
String, and firstOr, as
declared, returns an Int.
Note what the error does not say: it does not blame the definition, which
would be fine with any type. It blames the signature, and the fix is to
generalise it back to a -> [a] -> a. A
signature is a claim about all the call sites at once, which is why it is
worth writing before the body.
Exercises
- Start ghci and ask for the type of 1, 1.0 and [1]. Which of the three mentions a constraint?
- Give firstOr the signature a -> [a] -> a again and call it with Nothing as the fallback and a list of Just 1. Does it compile, and what does that prove?
- Write second :: [a] -> a and make it return the second element. What happens on a list with one element, and does the type warn you?
- Ask :type sort and :type sortBy in a shell where Data.List is imported. Which constraint appears, and why is it not there in the type of reverse?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
In a type signature, what does a lowercase name such as a stand for?
Answer
A type variable that any type can fill
Lowercase names in a signature are type variables, and every occurrence of one name must be the same type.
-
What does
Num a =>in a signature mean?Answer
a may be any type that has a Num instance
The part before => is a constraint: the caller may use any type that has an instance of the class.
-
Which of these is a synonym for String?
Answer
[Char]
String is defined as [Char], which is why every list function works on a string.
-
What does the compiler do with a type signature that does not match the definition?
Answer
It reports an error and builds nothing
The signature and the inferred type are unified, and a mismatch is an error that stops the build.
-
Which type does GHC infer for
add a b = a + b?Answer
Num a => a -> a -> a
Both arguments must have the same type, the result has that type, and the use of (+) adds the Num constraint.
-
What does this program print?
module Main (main) where firstOr :: a -> [a] -> a firstOr fallback [] = fallback firstOr _ (x : _) = x main :: IO () main = putStrLn (firstOr "none" ["one", "two"])Answer
one
The list is not empty, so firstOr returns its first element, and putStrLn prints the string without quotes.
-
What does this program print?
module Main (main) where firstOr :: a -> [a] -> a firstOr fallback [] = fallback firstOr _ (x : _) = x main :: IO () main = print (firstOr (0 :: Int) [])Answer
0
The first equation matches the empty list and returns the fallback, which is 0.
-
What does this program print?
module Main (main) where main :: IO () main = print (length "abcd")Answer
4
A String is a list of characters, and length counts its four elements.
-
A signature says
f :: Int -> Intbut the body uses its argument in a string concatenation. What is the result of the build?Answer
An error about Int and [Char], and no binary
The body needs a [Char] where the signature promises an Int, so the type checker reports a mismatch before any code is generated.
-
What does
:type 1print in GHCi?Answer
1 :: Num a => a
A numeric literal is polymorphic until its use fixes it, so GHCi shows the general type with its Num constraint.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev