Skip to content
AgileLogics
4 min read

Your First Program

Prerequisites: Installing Haskell

Create a file named hello.hs, and run it with runghc hello.hs:

main :: IO ()
main = do
  putStrLn "Hello, world!"
  putStrLn "Welcome to Haskell."

Expected output

Hello, world!
Welcome to Haskell.

Line by line:

  • main :: IO () is a type signature: main is an IO action that produces nothing interesting ((), pronounced "unit"). Every program starts at main.
  • main = do ... defines it. A do block runs several actions in order. The lines inside must be indented by the same amount.
  • putStrLn prints a string followed by a new line. Strings use double quotes.
  • There are no parentheses around function arguments: putStrLn "Hi" calls putStrLn with "Hi".

print and show

main :: IO ()
main = do
  print 42
  print (6 * 7)
  print "a string"
  putStrLn ("The answer is " ++ show 42)
42
42
"a string"
The answer is 42
  • print displays any showable value. For strings it shows the quotes, because it prints the value the way you would write it in code.
  • show turns a value into a String, and ++ joins two strings.
  • print (6 * 7) needs the parentheses — without them it would mean "call print with 6, then multiply by 7", which is a type error.

Compiling

ghc hello.hs
./hello          # hello.exe on Windows

ghc produces a native executable (plus .hi and .o files you can ignore). It starts instantly and runs much faster than runghc.

Practice

Write a program that prints your name on one line and the result of 2 ^ 10 on the next.

Show solution
main :: IO ()
main = do
  putStrLn "Ada"
  print (2 ^ 10)
Ada
1024