Chapter 2. Types and Functions
Why Care About Types?
Every expression and function in Haskell has a
type. For example, the value True
has the type Bool, while the
value "foo"
has the type
String. The type of a value indicates that it shares
certain properties with other values of the same type. For example, we
can add numbers and concatenate lists; these are properties of those
types. We say an expression has type X
, or is of type X
.
Before we launch into a deeper discussion of Haskell’s type system, let’s talk about why we should care about types at all—what are they even for? At the lowest level, a computer is concerned with bytes, with barely any additional structure. What a type system gives us is abstraction. A type adds meaning to plain bytes: it lets us say “these bytes are text,” “those bytes are an airline reservation,” and so on. Usually, a type system goes beyond this to prevent us from accidentally mixing up types. For example, a type system usually won’t let us treat a hotel reservation as a car rental receipt.
The benefit of introducing abstraction is that it lets us forget or ignore low-level details. If I know that a value in my program is a string, I don’t have to know the intimate details of how strings are implemented. I can just assume that my string is going to behave like all the other strings I’ve worked with.
What makes type systems interesting is that they’re not all equal. In fact, different type systems are often not even concerned with the same kinds of problems. ...
Get Real World Haskell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.