Haskell, lesson 1
A Haskell program starts at a value called main. Its type is IO (), which you can read as
"an action that talks to the outside world and gives back nothing interesting". When you press
Run, GHC compiles your file and then performs that action.
The first line is a type signature: it says what main is. The second line defines it.
Haskell can usually work out types on its own, but writing the signature for top-level
definitions is good style and gives you clearer error messages.
Notice there are no parentheses around the argument. In Haskell you call a function by
writing its name, a space, and the argument: putStrLn "Hi".
doTo run several actions one after another, put them in a do block. Each action goes on its
own line, indented by the same amount:
Haskell uses this instead of braces or semicolons, so keep the lines lined up.
2 exercises to try what you just read.
putStrLn prints a string and then a new line.putStr prints a string and stays on the same line.print prints any showable value, such as a number or a list, followed by a new line.That last line is a common surprise. print displays a value the way you would write it in
code, so a string comes out with its quotes. Use putStrLn for text you want people to read.
Also note print (6 * 7). Without the parentheses Haskell would read print 6 * 7 as
(print 6) * 7, which is an error. Function calls bind tighter than operators.
A string goes between double quotes. A backslash starts an escape: \n is a new line and
\" is a quote inside the string. Single quotes are for a single character ('A'), which has
a different type, Char.
GHC compiles the whole file before anything runs. It checks every type, and if something does not fit, you get a type error that names the line and says what it expected and what it found. These messages look long at first; read the first few lines, which say the most. Compiling takes a few seconds, so Run is slower than in a scripting language.
Write a program that prints exactly these two lines:
The program reads no input.
Print this little scoreboard. Build the first line with two putStr calls ("Score: " and
"Home ") and one putStrLn ("vs Away"). Then use print to show the result of 3 + 4,
and putStrLn for the last line.
main :: IO ()
main = putStrLn "Hello, World!"main :: IO ()
main = do
putStrLn "Booting..."
putStrLn "Ready."main :: IO ()
main = do
putStr "Loading"
putStr "..."
putStrLn "done" -- Loading...done
print 42 -- 42
print (6 * 7) -- 42
print "quoted" -- "quoted" (print shows the quotes!)-- A line comment starts with two dashes.
{- A block comment
can span several lines. -}Hello, World!
I am learning Haskell.Score: Home vs Away
7
Game over