Your first program

The file

A Haskell program is a module with a function called main. Create a file named Main.hs and put two lines in it:

main :: IO () main = putStrLn "Hello, world!"

The signature says that main performs input and output and returns nothing interesting, which the unit type () expresses. The second line is the body: call putStrLn with one string.

Run it

runghc interprets the file without producing an executable. It is the quick loop for experiments:

runghc Main.hs

Hello, world!

Compile it

ghc produces a native binary. The default output name drops the extension and keeps the module name, so the program is called Main:

ghc Main.hs

[1 of 2] Compiling Main ( Main.hs, Main.o ) [2 of 2] Linking Main

./Main

Hello, world!

ghc -O2 Main.hs enables optimisations, and ghc -o hello Main.hs chooses the binary name. Compilation artefacts land in the current directory, which is why real projects use Cabal instead.

The layout rule

Haskell has no braces for a block. Indentation defines it: lines that start in the same column belong together. A do block lines up its statements:

main = do putStrLn "What is your name?" name <- getLine putStrLn ("Hello, " ++ name)

Mixing tabs and spaces breaks the rule in ways the error message rarely explains. Configure the editor to insert four spaces for a tab in .hs files and the problem disappears.

The code on this page was run with GHC 9.10.3 and runghc 9.10.3 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev