Your first program
| The file | |
| Run it | |
| Compile it | |
| The layout rule |
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, so the program is called main:
ghc Main.hs
[1 of 1] Compiling Main ( Main.hs, Main.o ) 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.
Next:
Values with let and where
Article author: Arthur Isaev