Chapter 3. Defining Types, Streamlining Functions
Defining a New Data Type
Although lists and tuples are useful, we’ll often want to construct new data types of our own. This allows us to add structure to the values in our programs. Instead of using an anonymous tuple, we can give a collection of related values a name and a distinct type. Defining our own types also improves the type safety of our code: Haskell will not allow us to accidentally mix values of two types that are structurally similar but have different names.
For motivation, we’ll consider a few kinds of data that a small online bookstore might need to manage. We won’t make any attempt at complete or realistic data definitions, but at least we’re tying them to the real world.
We define a new data type using the data
keyword:
-- file: ch03/BookStore.hs data BookInfo = Book Int String [String] deriving (Show)
BookInfo after the
data
keyword is the name of our new type. We call
BookInfo a type constructor.
Once we define a type, we will use its type constructor to
refer to it. As we’ve already mentioned, a type name, and hence a type
constructor, must start with a capital letter.
The Book
that follows is the name of
the value constructor (sometimes called
a data constructor). We use this to create a value of the
BookInfo
type. A value constructor’s name must also start
with a capital letter.
After Book
, the
Int
, String
, and [String]
that
follow are the components of the type. A component serves the same purpose in Haskell as ...
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.