Defining Custom Data Types

Introduction: Beyond Type Synonyms

Welcome to the second unit of our course! In our previous lesson, you learned how to use the type keyword to create type synonyms. As a quick reminder, we used statements like type Title = String to give new, descriptive names to existing data types. This helped make our code much easier to read.

However, type synonyms only rename things that already exist. Today, we are taking a big step forward. We are going to learn how to build our own completely new data models from scratch using the data keyword. By the end of this lesson, you will be able to define custom types to perfectly fit the needs of your programs.

Creating Simple Choices: The data Keyword

Let's start by looking at how to define a custom type that represents a simple choice. Imagine that we want to track whether a task is unfinished or finished. We can create a brand-new type called Status.

Haskell
data Status = Todo | Done

In this code, data is the keyword telling Haskell that we are creating a new type. Status is the name of our new type.

On the right side of the equal sign, we have Todo | Done. Todo and Done are called constructors. You can think of constructors as the specific, named values that our new type is allowed to be. The vertical bar | simply means "or." So, a Status can be either Todo or Done.

However, there is a catch. By default, Haskell does not automatically know how to print custom types to the screen, and it does not automatically know how to check if two custom values are equal. If we try to write print Todo right now, the program will fail to compile because Haskell cannot find a Show Status instance.

To fix this in a simple beginner-friendly way, we can ask Haskell to create these standard instances for us by adding a small piece of code to the end of our definition:

Haskell
data Status = Todo | Done
  deriving (Show, Eq)

Adding deriving (Show, Eq) automatically creates two useful instances for our custom type:

  • Show teaches Haskell how to convert our type into text so that it can be printed to the screen.
  • Eq (short for equality) teaches Haskell how to compare two values using the == symbol to see if they are the same.

A Show instance is required for print, and an Eq instance is required for ==. In more advanced Haskell, programmers can write these instances by hand, but in this course we will use deriving (Show, Eq) as the simplest way to create them.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal