Now that you have some experience evaluating expressions, it’s time to write your first complete Haskell program. We’ll start with an obligatory “Hello World” program by creating a new empty file named Main.hs in your Chapter1 directory.
Open Main.hs and copy this example:
| | module Main where |
| | main = print "Hello, World!" |
You’ll learn what each of these lines is doing as you work your way through the chapter, but for now let’s build the application and run your program.
From your command line you can compile your program by typing ghc Main. After the program is built you’ll have a new executable, Main, that you can run to see your message:
| | user@host$ ghc Main |
| | [1 of 1] Compiling Main ( Main.hs, Main.o ) |
| | Linking Main ... |
| | user@host$ ./Main |
| | "Hello, World!" |
Compiling your program upfront makes sense if you’re going to run your program several times, but if you just want to run it once or twice while you are developing it, then you can skip the separate compilation step and just run your module by calling runhaskell Main.hs:
| | user@host$ runhaskell Main.hs |
| | "Hello, World!" |
As an alternative to runhaskell you can also load your module directly into ghci using the :load command. Loading your module into ghci not only lets you run your main function, like in the following example, but also gives you access to all of the other functions and variables that are in scope. Loading modules for interactive testing while you are actively developing code is a great way to design better APIs and get a feel for how your code is working. Just keep in mind that code running in ghci won’t be as performant as code compiled ahead of time.
Open ghci from the Chapter1 directory where you saved Main.hs and load your module and run Main.hs:
| | λ :load Main.hs |
| | λ main |
| | "Hello, World!" |
Congratulations! You’ve written and executed your very first Haskell program. To write something more sophisticated, you’ll need to learn some more syntax.