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:mainis an IO action that produces nothing interesting ((), pronounced "unit"). Every program starts atmain.main = do ...defines it. Adoblock runs several actions in order. The lines inside must be indented by the same amount.putStrLnprints a string followed by a new line. Strings use double quotes.- There are no parentheses around function arguments:
putStrLn "Hi"callsputStrLnwith"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
printdisplays any showable value. For strings it shows the quotes, because it prints the value the way you would write it in code.showturns a value into aString, and++joins two strings.print (6 * 7)needs the parentheses — without them it would mean "callprintwith6, 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