One of Haskell’s greatest strengths is its powerful type system.
In Haskell, every expression’s type is known at compile time, which leads to safer code. If you write a program that tries to divide a Boolean type with a number, it won’t compile. This is good because it’s better to catch those kinds of errors at compile time, rather than having your program crash later on. Everything in Haskell has a type, so the compiler can reason quite a lot about your program before compiling it.
Unlike Java or Pascal, Haskell has type inference. If we write a number, for example, we don’t need to tell Haskell it’s a number, because it can infer that on its own.
So far, we’ve covered some of the basics of Haskell with only a very superficial glance at types, but understanding the type system is a very important part of learning Haskell.
Explicit Type Declaration
We can use GHCi to examine the types of some expressions. We’ll do that by using the :t command which, followed by any valid expression, tells us its type. Let’s give it a whirl:
ghci> :t 'a'
'a' :: Char
ghci> :t True
True :: Bool
ghci> :t "HELLO!"
"HELLO!" :: [Char]
ghci> :t (True, 'a')
(True, 'a') :: (Bool, Char)
ghci> :t 4 == 5
4 == 5 :: Bool
The :: operator here is read as “has type of.” Explicit types are always denoted with the first letter in uppercase. 'a' has a type of Char , which stands for character . True is a Bool , or a Boolean type. "HELLO!" , which is a string, shows its type as [Char] . The square brackets denote a list, so we read that as it being a list of characters. Unlike lists, each tuple length has its own type. So the tuple (True, 'a') has a type of (Bool, Char) , and ('a','b','c') has a type of (Char, Char, Char) . 4 == 5 will always return False , so its type is Bool .
Functions also have types. When writing our own functions, we can choose to give them an explicit type declaration. This is generally considered to be good practice (except when writing very short functions). From here on, we’ll give all the functions that we make type declarations.
Remember the list comprehension we made in Chapter 1 —the one that filters out a string’s lowercase letters? Here’s how it looks with a type declaration:
removeNonUppercase :: [Char] -> [Char]
removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z']]
The removeNonUppercase function has a type of [Char] -> [Char] , meaning that it takes one string as a parameter and returns another as a result.
But how do we specify the type of a function that takes several parameters? Here’s a simple function that takes three integers and adds them together:
addThree :: Int -> Int -> Int -> Int
addThree x y z = x + y + z
The parameters and the return type are separated by -> characters, with the return type always coming last in the declaration. (In Chapter 5 , you’ll see why they’re all separated with -> , instead of having a more explicit distinction.)
If you want to give your function a type declaration, but are unsure as to what it should be, you can always just write the function without it, and then check it with :t . Since functions are expressions, :t works on them in the same way as you saw at the beginning of this section.
Common Haskell Types
Let’s take a look at some common Haskell types, which are used for representing basic things like numbers, characters, and Boolean values. Here’s an overview:
-
Intstands for integer. It’s used for whole numbers.7can be anInt, but7.2cannot.Intis bounded , which means that it has a minimum value and a maximum value.Note
We’re using the GHC compiler, where the range of
Intis determined by the size of a machine word on your computer. So if you have a 64-bit CPU, it’s likely that the lowestInton your system is -2 63 , and the highest is 2 63 –1. -
Integeris also used to store integers, but it’s not bounded, so it can be used to represent really big numbers. (And I mean really big!) However,Intis more efficient. As an example, try saving the following function to a file:factorial :: Integer -> Integer factorial n = product [1..n]Then load it into GHCi with
:land test it:ghci> factorial 50 30414093201713378043612608166064768844377641568960512000000000000 -
Floatis a real floating-point number with single precision. Add the following function to the file you’ve been working in:circumference :: Float -> Float circumference r = 2 * pi * rThen load and test it:
ghci> circumference 4.0 25.132742 -
Doubleis a real floating-point number with double the precision. Double-precision numeric types use twice as many bits to represent numbers. The extra bits increase their precision at the cost of hogging more memory. Here’s another function to add to your file:circumference' :: Double -> Double circumference' r = 2 * pi * rNow load and test it. Pay particular attention to the difference in precision between
circumferenceandcircumference'.ghci> circumference' 4.0 25.132741228718345 -
Boolis a Boolean type. It can have only two values:TrueandFalse. -
Charrepresents a Unicode character. It’s denoted by single quotes. A list of characters is a string. -
Tuples are types, but their definition depends on their length as well as the types of their components. So, theoretically, there is an infinite number of tuple types. (In practice, tuples can have at most 62 elements—far more than you’ll ever need.) Note that the empty tuple
()is also a type, which can have only a single value:().
Type Variables
It makes sense for some functions to be able to operate on various types. For instance, the head function takes a list and returns the head element of that list. It doesn’t really matter if the list contains numbers, characters, or even more lists! The function should be able to work with lists that contain just about anything.
What do you think the type of the head function is? Let’s check with the :t function:
ghci> :t head
head :: [a] -> a
What is this a ? Remember that type names start with capital letters, so it can’t be a type. This is actually an example of a type variable , which means that a can be of any type.
Type variables allow functions to operate on values of various types in a type-safe manner. This is a lot like generics in other programming languages. However, Haskell’s version is much more powerful, since it allows us to easily write very general functions.
Functions that use type variables are called polymorphic functions . The type declaration of head states that it takes a list of any type and returns one element of that type.
Note
Although type variables can have names that are longer than one character, we usually give them names like a , b , c , d , and so on.
Remember fst ? It returns the first item in a pair. Let’s examine its type:
ghci> :t fst
fst :: (a, b) -> a
You can see that fst takes a tuple and returns an element that is of the same type as its first item. That’s why we can use fst on a pair that contains items of any two types. Note that even though a and b are different type variables, they don’t necessarily need to be different types. This just means that the first item’s type and the return value’s type will be the same.
Type Classes 101
A type class is an interface that defines some behavior. If a type is an instance of a type class, then it supports and implements the behavior the type class describes.
More specifically, a type class specifies a bunch of functions, and when we decide to make a type an instance of a type class, we define what those functions mean for that type.
A type class that defines equality is a good example. The values of many types can be compared for equality by using the == operator. Let’s check the type signature of this operator:
ghci> :t (==)
(==) :: (Eq a) => a -> a -> Bool
Note that the equality operator ( == ) is actually a function. So are + , * , - , / , and almost every other operator. If a function is composed of only special characters, it’s considered an infix function by default. If we want to examine its type, pass it to another function, or call it as a prefix function, we need to surround it in parentheses, as in the preceding example.
This example shows something new: the => symbol. Everything before this symbol is called a class constraint . We can read this type declaration like this: The equality function takes any two values that are of the same type and returns a Bool . The type of those two values must be an instance of the Eq class.
The Eq type class provides an interface for testing for equality. If it makes sense for two items of a particular type to be compared for equality, then that type can be an instance of the Eq type class. All standard Haskell types (except for input/output types and functions) are instances of Eq .
Note
It’s important to note that type classes are not the same as classes in object-oriented programming languages.
Let’s look at some of the most common Haskell type classes, which enable our types to be easily compared for equality and order, printed as strings, and so on.
The Eq Type Class
As we’ve discussed, Eq is used for types that support equality testing. The functions its instances implement are == and /= . This means that if there’s an Eq class constraint for a type variable in a function, it uses == or /= somewhere inside its definition. When a type implements a function, that means it defines what the function does when used with that particular type. Here are some examples of performing these operations on various instances of Eq :
ghci> 5 == 5
True
ghci> 5 /= 5
False
ghci> 'a' == 'a'
True
ghci> "Ho Ho" == "Ho Ho"
True
ghci> 3.432 == 3.432
True
The Ord Type Class
Ord is a type class for types whose values can be put in some order. For example, let’s look at the type of the greater-than ( > ) operator:
ghci> :t (>)
(>) :: (Ord a) => a -> a -> Bool
The type of > is similar to the type of == . It takes two items as parameters and returns a Bool , which tells us if some relation between those two things holds or not.
All the types we’ve covered so far (again, except for functions) are instances of Ord . Ord covers all the standard comparison functions such as > , < , >= , and <= .
The compare function takes two values whose type is an Ord instance and returns an Ordering . Ordering is a type that can be GT , LT , or EQ , which represent greater than, lesser than, or equal, respectively.
ghci> "Abrakadabra" < "Zebra"
True
ghci> "Abrakadabra" `compare` "Zebra"
LT
ghci> 5 >= 2
True
ghci> 5 `compare` 3
GT
ghci> 'b' > 'a'
True
The Show Type Class
Values whose types are instances of the Show type class can be represented as strings. All the types we’ve covered so far (except for functions) are instances of Show . The most commonly used function that operates on instances of this type class is show , which prints the given value as a string:
ghci> show 3
"3"
ghci> show 5.334
"5.334"
ghci> show True
"True"
The Read Type Class
Read can be considered the opposite type class of Show . Again, all the types we’ve covered so far are instances of this type class. The read function takes a string and returns a value whose type is an instance of Read :
ghci> read "True" || False
True
ghci> read "8.2" + 3.8
12.0
ghci> read "5" - 2
3
ghci> read "[1,2,3,4]" ++ [3]
[1,2,3,4,3]
So far so good. But what happens if we try entering read "4" ?
ghci> read "4"
*** Exception: Prelude.read:no parse
GHCi is telling us that it doesn’t know what we want in return. Notice that in the previous uses of read , we did something with the result afterward, which let GHCi infer the kind of result we wanted. If we used it as a Boolean, for example, it knew it had to return a Bool . But now it knows we want some type that is part of the Read class, but it doesn’t know which one. Let’s take a look at the type signature of read :
ghci> :t read
read :: (Read a) => String -> a
Note
String is just another name for [Char] . String and [Char] can be used interchangeably, but we’ll mostly be sticking to String from now on because it’s easier to write and more readable.
We can see that the read function returns a value whose type is an instance of Read , but if we use that result in some way, it has no way of knowing which type. To solve this problem, we can use type annotations .
Type annotations are a way to explicitly tell Haskell what the type of an expression should be. We do this by adding :: to the end of the expression and then specifying a type:
ghci> read "5" :: Int
5
ghci> read "5" :: Float
5.0
ghci> (read "5" :: Float) * 4
20.0
ghci> read "[1,2,3,4]" :: [Int]
[1,2,3,4]
ghci> read "(3, 'a')" :: (Int, Char)
(3, 'a')
The compiler can infer the type of most expressions by itself. However, sometimes the compiler doesn’t know whether to return a value of type Int or Float for an expression like read "5" . To see what the type is, Haskell would need to actually evaluate read "5" . But since Haskell is a statically typed language, it needs to know all the types before the code is compiled (or in the case of GHCi, evaluated). So we need to tell Haskell, “Hey, this expression should have this type, in case you didn’t know!”
We can give Haskell only the minimum amount of information it needs to figure out which type of value read should return. For instance, if we’re using read and then cramming its result into a list, Haskell can use the list to figure out which type we want by looking at the other elements of the list:
ghci> [read "True", False, True, False]
[True, False, True, False]
Since we used read "True" as an element in a list of Bool values, Haskell sees that the type of read "True" must also be Bool .
The Enum Type Class
Enum instances are sequentially ordered types—their values can be enumerated. The main advantage of the Enum type class is that we can use its values in list ranges. They also have defined successors and predecessors, which we can get with the succ and pred functions. Some examples of types in this class are () , Bool , Char , Ordering , Int , Integer , Float , and Double .
ghci> ['a'..'e']
"abcde"
ghci> [LT .. GT]
[LT,EQ,GT]
ghci> [3 .. 5]
[3,4,5]
ghci> succ 'B'
'C'
The Bounded Type Class
Instances of the Bounded type class have an upper bound and a lower bound, which can be checked by using the minBound and maxBound functions:
ghci> minBound :: Int
-2147483648
ghci> maxBound :: Char
'\1114111'
ghci> maxBound :: Bool
True
ghci> minBound :: Bool
False
The minBound and maxBound functions are interesting because they have a type of (Bounded a) => a . In a sense, they are polymorphic constants.
Note that tuples whose components are all instances of Bounded are also considered to be instances of Bounded themselves:
ghci> maxBound :: (Bool, Int, Char)
(True,2147483647,'\1114111')
The Num Type Class
Num is a numeric type class. Its instances can act like numbers. Let’s examine the type of a number:
ghci> :t 20
20 :: (Num t) => t
It appears that whole numbers are also polymorphic constants. They can act like any type that’s an instance of the Num type class ( Int , Integer , Float , or Double ):
ghci> 20 :: Int
20
ghci> 20 :: Integer
20
ghci> 20 :: Float
20.0
ghci> 20 :: Double
20.0
For example, we can examine the type of the * operator:
ghci> :t (*)
(*) :: (Num a) => a -> a -> a
This shows that * accepts two numbers and returns a number of the same type. Because of this type constraint, (5 :: Int) * (6 :: Integer) will result in a type error, while 5 * (6 :: Integer) will work just fine. 5 can act like either an Integer or an Int , but not both at the same time.
To be an instance of Num , a type must already be in Show and Eq .
The Floating Type Class
The Floating type class includes the Float and Double types, which are used to store floating-point numbers.
Functions that take and return values that are instances of the Floating type class need their results to be represented with floating-point numbers in order to do meaningful computations. Some examples are sin , cos , and sqrt .
The Integral Type Class
Integral is another numeric type class. While Num includes all numbers, including real number integers, the Integral class includes only integral (whole) numbers. This type class includes the Int and Integer types.
One particularly useful function for dealing with numbers is fromIntegral . It has the following type declaration:
fromIntegral :: (Integral a, Num b) => a -> b
Note
Notice that fromIntegral has several class constraints in its type signature. That’s completely valid—multiple class constraints are separated by commas inside the parentheses.
From its type signature, we can see that fromIntegral takes an integral number and turns it into a more general number. This is very useful when you want integral and floating-point types to work together nicely. For instance, the length function has this type declaration:
length :: [a] -> Int
This means that if we try to get the length of a list and add it to 3.2 , we’ll get an error (because we tried to add an Int to a floating-point number). To get around this, we can use fromIntegral , like this:
ghci> fromIntegral (length [1,2,3,4]) + 3.2
7.2
Some Final Notes on Type Classes
Because a type class defines an abstract interface, one type can be an instance of many type classes, and one type class can have many types as instances. For example, the Char type is an instance of many type classes, two of them being Eq and Ord , because we can check if two characters are equal as well as compare them in alphabetical order.
Sometimes a type must first be an instance of one type class to be allowed to become an instance of another. For example, to be an instance of Ord , a type must first be an instance of Eq . In other words, being an instance of Eq is a prerequisite for being an instance of Ord . This makes sense if you think about it, because if you can compare two things for ordering, you should also be able to tell if those things are equal.