O'Reilly logo

Real World Haskell by Donald Bruce Stewart, Bryan O'Sullivan, John Goerzen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Algebraic Data Types

The familiar Bool is the simplest common example of a category of type called an algebraic data type. An algebraic data type can have more than one value constructor:

-- file: ch03/Bool.hs
data Bool = False | True

The Bool type has two value constructors, True and False. Each value constructor is separated in the definition by a | character, which we can read as or—we can construct a Bool that has the value True, or the value False. When a type has more than one value constructor, they are usually referred to as alternatives or cases. We can use any one of the alternatives to create a value of that type.

A note about naming

Although the phrase algebraic data type is long, we’re being careful to avoid using the acronym ADT, which is already widely understood to stand for abstract data type. Since Haskell supports both algebraic and abstract data types, we’ll be explicit and avoid the acronym entirely.

Each of an algebraic data type’s value constructors can take zero or more arguments. As an example, here’s one way we might represent billing information:

-- file: ch03/BookStore.hs
type CardHolder = String
type CardNumber = String
type Address = [String]

data BillingInfo = CreditCard CardNumber CardHolder Address
                 | CashOnDelivery
                 | Invoice CustomerID
                   deriving (Show)

Here, we’re saying that we support three ways to bill our customers. If they want to pay by credit card, they must supply a card number, the holder’s name, and the holder’s billing address as arguments ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required