Let's revisit our first program (Hello.hs) from day one.
module Main where
message = "Good bye imperative world!"
main = putStrLn message
I have defined message to be "Good bye imperative world!". In Haskell message is not a variable. It is the name of the given expression. "=" stands for definition not assignment. There are no variables in Haskell, expressions are immutable.
- Try to assign a new value to message and compile Hello.hs.
module Main where
message = "Good bye imperative world!"
message = "Hello Haskell!"
main = putStrLn message
It is good practice to give type signature to expressions. The previous example with type declaration looks like this:
module Main where
message :: String
message = "Good bye imperative world!"
main :: IO ()
main = putStrLn message
message is of type String and main is of type IO (). Do not let the type of main intimidate you. We will get there soon.
- Add type annotations to the following Haskell program.
module Main where
someNumber = [1..10]
main = print someNumber
Functions are first class citizens in Haskell. This means that they can be passed as an argument or returned from a function. Haskell function definitions do not differ from ordinary definitions much. The function name is followed by the parameter names, an equal sign and the function definition. However type signature can be strange at first sight. The function name is followed by double colon and the parameter types separated by ->. The last type is the return value of the function.
double :: Int -> Int
double n = n * 2
times :: Int -> Int -> Int
times n multiplier = n * multiplier
The double function takes an Int as the first parameter and returns an Int. The times function takes two Int parameters and returns an Int.
Calling a Haskell function is the most natural thing in the language. Just follow the function name with the parameters.
double 10
times 2 10
putStrLn "Hello world!"
Function application associates to the left and has the highest precedence.
You can load your source files in to ghci and run your functions separately with the :l command. If the file changes it is enough to use the reload command :r.
Prelude> :l Hello.hs
[1 of 1] Compiling Main ( <filename>, interpreted )
Ok, modules loaded: Main.
*Main> message
"Good bye imperative world!"
This way you can try out your functions without getting into trouble with IO.
- Write a function named palindrom that returns true if the only string parameter it has is a palindrome and false otherwise. Test your function by loading it into ghci.
- Correct the following Haskell program.
- Add type declaration to all functions below.
module Main where
double n = n * 2
times n multiplier = n * multiplier
calculation = times double 10 20
main = print calculation