# Defining Types with data

Let's learn to define our own Haskell data types.

We'll cover the following

So far, we have worked exclusively with the predefined types of Haskell, such as numbers, strings, and lists. In this chapter, we will learn how to create our own data types.

Working with our own types has advantages for both the readability and safety of our code. To illustrate this, let’s revisit the function perimeter, which we wrote in a previous lesson to compute the perimeter of a rectangle.

perimeter :: (Double, Double) -> Double
perimeter (a, b) = 2 * a + 2 * b


This function takes two double inputs. But from reading the type definition, it is not clear that these two doubles are the sides of a rectangle. Furthermore, one could call the function with any two doubles, even when there is no association between them.

Both issues can be solved by having a custom Rectangle type and defining:

perimeter :: Rectangle -> Double
perimeter (Rectangle width height) = 2 * width + 2 * height


It is now clear that perimeter works on rectangles, and the compiler can verify that it only calls on rectangles. We will now learn how to create such types.

Get hands-on with 1200+ tech skills courses.