Your First Haskell Program
Introduction: Your First Haskell Program
Welcome to the first lesson of our Haskell Programming for Beginners course! In this first unit of seven, we are going to dive right in and create a working program.
By the end of this lesson, you will be able to write, run, and read the output of a real Haskell program from scratch. Specifically, we will build a short script that prints out a greeting and a message to the screen. To do this, we will learn how to set up the starting point of our program and how to tell the computer to display text.
The Starting Point: main
Every Haskell program needs a designated starting point so the computer knows exactly where to begin reading and executing your instructions. In Haskell, this starting point is always called main.
Let us write the very first line of our program:
In this code snippet, we are giving Haskell a label and a type.
- The word
mainis the name of our starting point. - The
::symbol can be read as "has the type of." - The
IO ()part is a special instruction that tells Haskell, "This part of the program is going to interact with the outside world."IOstands for Input/Output. Because printing text to a screen is an action that interacts with the real world, we must include this label.
Printing Text with putStrLn
Now that we have declared our starting point, we need to give main some actual work to do. We will use a command called putStrLn to display text on the screen.
Let us update our code to print a single greeting:
Here is what is happening:
- We use the equals sign (
=) to say thatmainis defined by the action that follows. putStrLnstands for "put string and add a new line." Astringis simply a programming term for a sequence of text characters.- We wrap our text (
"Hello from Haskell!") in double quotation marks. This is how Haskell knows where our text begins and ends.
If we run this code, the output on the screen will look exactly like this:
Doing More Than One Thing: The do Block
Often, you will want your program to perform more than one action. For example, we might want to print a second line of text immediately after the first one.
Because Haskell evaluates instructions a bit differently from other programming languages, we need to explicitly tell it to run our commands sequentially from top to bottom. We do this using the do keyword.
Let us expand our program to print two separate lines:
Notice the changes we made:
- We added the word
doright after the equals sign. This creates adoblock, which groups multiple actions together in order. - We moved our
putStrLncommands to the lines below thedokeyword. - We indented both
putStrLncommands. In Haskell, indentation is very important. All commands inside adoblock must line up vertically so Haskell knows they belong together.
When we run this completed code, the output will show both lines in the exact order we wrote them:
