Naming Your Domain

Introduction: Speaking the Language of Your App

Welcome to the very first unit of our "Haskell Programming for Beginners" course! Over the next seven units, we will be learning Haskell by building a command-line task manager.

When writing programs, we often use basic data types built into the language. For example, we use Int for numbers and String for text. However, if we use Int and String for everything, our code can become confusing. If you see a function that requires an Int, is that number meant to be an age, a price, or a task ID?

To solve this, we want to create a "domain vocabulary." This means we want to name our types after the real-world concepts they represent. By the end of this lesson, you will learn how to give standard types clear, descriptive nicknames. This will make your code much easier to read and understand.

A Quick Refresher: Strings, show, and Printing

Before we create our new types, let us briefly look at a few basic tools we will use to build our code today. Since our goal is to format and display task details on the screen, we need to know how to work with text.

In Haskell, you can join two pieces of text (strings) together using the ++ symbol.

Haskell
"Hello " ++ "World"

If you have a number, you cannot directly join it to a string. First, you must convert the number into a string using a built-in tool called show.

Haskell
"Task number: " ++ show 1

Finally, to print text so the user can see it on the screen, we use putStrLn (which stands for "put string line"). We will use these three basic tools — ++, show, and putStrLn — to display our tasks later in the lesson.

Creating Nicknames with the type Keyword

Now, let us introduce our main topic. In our task manager, every task will have an ID number and a text title. Instead of just calling them Int and String, we can declare a type synonym using the type keyword.

Haskell
type TaskId = Int
type Title = String

In this code, we are telling Haskell: "From now on, the name TaskId means the exact same thing as Int, and Title means the exact same thing as String."

The most important rule to remember is that the type keyword does not create a brand-new type. It only creates an alias, or a nickname. A TaskId is still just a regular Int under the hood. It follows all the exact same rules as a normal number.

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