Exercises for Week 1: Getting Started With Haskell
This excersise set is designed as very very gentle introduction to Haskell and the interactive Haskell interpreter GHCi. You will need to have access a working Haskell system either on your computer or the school's computers.
From week 2 onwards there are scheduled exercises classes where you can ask questions and get help.
You are supposed to work through this document in an afternoon. The main tasks are to answer questions that look like this:
The questions come with a suggested answer that you can see by clicking at the question mark symbol the left. Try to answer the questions yourself before looking!
GHCi as a simple calculatorGHCi is an Haskell interpreter, i.e. it is a program that evaluates Haskell expressions.
You can start GHCi by typing
in a terminal.
We will use
this stylefor the text that you as user of GHCi have to enter.
When you start GHCi you will see something like this welcome message:
GHCi, version 8.0.1: http://www.haskell.org/ghc/ :? for helpRight now, we don't care about the precise meaning of the text in the welcome message, but focus on the last line with the > symbol. The > symbol indicates that GHCi is ready to receive a command. We will explain later on what the word
Preludemeans. The simplest command one can give to GHCi is an Haskell expression, given an Haskell expression GHCi will evaluate it, and write the result on the screen. Try:
After that, as indicated by the > symbol, GHCi is ready to take a new command. We can repeat this interaction as many times as we want. Try:
The first expression contains asyntax error; there is no right operand of the multiplication operator (*). In the second expression we try to divide by zero. Recognizing different kinds of errors and knowing their causes will take some time to learn!
3+5*<interactive>:1:4: parse error (possibly incorrect indentation)
More GHCi commandsWe use the :q command to finish a GHCi session.
All GHCi commands except evaluating an expressions start with a colon
:qLeaving GHCi. candela04>
Restart GHCi and try to answer the following questions by inspecting the welcome message.
Two simple examples
A programmable pocket calculator
We have seen how we can use GHCi to do simple calculations. But this is just the beginning. To go further we need to define our own functions. As a first example we look at the currency conversion problem described above. If we need to repeatedly convert pounds to SEK we can define a function that does this for us. Defining a function consists of a number of steps.
- Decide upon a name for the function. A name should be chosen that
is suggestive of it's purpose, and
does not shadow a function currently in scope. For this example we chose
- Decide which arguments (input) the function has, and what the
result (output) of the function is. In this case this is simple:
- Input: a floating point number representing an amount of crowns.
- Output: a floating point number representing an an amount of pounds.
- Decide upon a name for the parameters of the function that
indicates the usage of the argument. In this case we use the name
- Express the result in terms of the parameters. In this case
the result is:
- Decide upon the type of the function. In this case:
pounds:: Double -> Double
- Write the complete Haskell function definition. In this case:
pounds :: Double -> Double pounds kr = kr/12.7775
- Use a text editor (Vim and Sublime text are two popular cross-platorm editors, gedit on linux, notepad++ on Windows, Atom for Mac are all examples) to write the function
definition in a file. Do this, start your editor and create a new file containing the definition above. Save this to a file with name
- Give GHCi a command to load the file
:l ex1.hsCompiling Main ( ex1.hs, interpreted ) Ok, modules loaded: Main. *Main>
ex1.hs. Load the file and test your function.
pount 10(note the spelling error). What happens if one writes:
Comparison and more complex functionsUp till now we have defined functions by equations of the form:
name parameter = an expressions containing the parameter, numbers and arithmetic operations.
It is not always this easy, consider the following example:
A shop sells potatoes for 3.50 SEK/kg. To stimulates large sales, the shop offers a discount of 3 SEK/kg for the quantity exceeding 10kg.
We want to define the function that calculates the price.
Let's call this function
price and the parameter
v is at most 10, then the price is
v is more than 10, the price is
35+3*(v-10) (check this!) which is equal to
5+3*v. So, we have:
How does one write this in Haskell? First, notice that GHCi can compare numbers.Try:
price(v) = 3.5*v, if
price(v) = 5+3*v, if
The result of such a comparison is either
3 < 6True
3.5 <= 3False
pounds 4000 > 3*100True
False. Notice, that smaller than or equal to is written as
<=. Now, we can write the definition of price as follows:
The Boolean expressions betweenprice :: Double -> Double price v | v <= 10 = 3.5*v | v > 10 = 5+3*v
=are called guards. When this function is applied to a particular argument, GHCi checks the guards from top to bottom until it finds one that evaluates to
True, after that the right-hand side of the expression is used to calculate the result. If all guards evaluate to
FalseGHCi gives an error message.
Load this function into GHCi, and test the function price on different arguments.
What is the result of applying the function to 9.5, 10.5 and 11.5, respectively?| v > 11 = 5+3*v
What is the now result of applying the function to 9.5, 10.5 and 11.5, respectively?price v | v <= 11 = 3.5*v | v > 10 = 5+3*v
otherwiseas a guard that is always true. So, if
otherwiseis used as the last guard, the expression at the right-hand side will be used if none of the other guards evaluates to true.
So, we can write:
price :: Double -> Double price v |v <= 10 = 3.5*v |otherwise = 5+3*v
otherwise a Haskell keyword? What does hoogle say?
When a function is applied to a simple argument (like 5) we don't need parentheses. But if the argument is composed (like 4 + 8) parentheses are needed.
Functions with more than one argumentFunctions can have more than one argument. As an example we define a function that defines the average of two numbers:
- The name of the function:
- Input: Two floating point numbers.
Output: A floating point number giving the average of the two arguments.
- Names of the parameters:
- The result in terms of the parameters:
- The type:
average :: Double -> Double -> Double
- The complete definition:
average :: Double -> Double -> Double average x y = (x+y)/2
average 5 86.5
The PreludeSome functions are very frequently used and therefore pre-defined in a module (file) called the Prelude, which is loaded automatically every time GHCi is started. An overview of the functions defined can be found in e.g., A Tour of the Haskell Prelude.
To be able to program efficiently in Haskell it is necessary to know which functions are available in the prelude. In the coming weeks you will become more familiar with them.
Operators and functions with two argumentsOperators like *,-,+ are written infix, which means that the operator should be between its arguments. Functions are usually written prefix, meaning that they are written in front of their arguments.
However, one can use a function infix by writing it between ` `. An operator can be used prefix by writing it in between parentheses. Try:
5 `average` 44.5
4 `max` (5 `max` 2)5
(+) 3 47
IntegersThe prelude provide the function
divfor integer division. Try:
div 17 53
div 34 84
div 5 90
4 `div` 22
modgives the remainder for integer division:
17 `mod` 52
34 `mod` 82
5 `mod` 95
mod 4 20
==which evaluates to
Trueif its arguments are equal.
A bigger example
Consider the following game:
Think of an whole number greater than one. If its even, divide it by two, otherwise multiply it by three and add one. Stop if the resulting number is one, otherwise repeat the procedure.As example, we start width 10.
- 10 is even, so the next number is: 10/2 = 5
- 5 is odd so the next number is: 3*5+1=16
- 16 is even, so the next number is: 16/2 = 8
- 8 is even, so the next number is: 8/2 = 4
- 4 is even, so the next number is: 4/2 = 2
- 2 is even, so the next number is: 1.
If we start with 7 we get: (Check this!)
7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1.
We are interested in the question: Given a number n, how many numbers are there in the sequence? For n=10, we get 7 numbers (10, 5, 16, 8, 4, 2, 1). For n=7 we get 17 numbers (See above). Note that we include both the number n we start with and the final number 1.
How can GHCi help us to answer the question? We start with defining
next that given a number computes the next number
in the sequence.
stepsthat takes a number
nas argument and calculates the length of the generated sequence. What is
steps 20? And
We call this a recursive definition. (You should have met this concept before - otherwise ask for a refund on your undergraduate education!) Write the definition in your file. Load it in to GHCi, and calculatesteps :: Int -> Int steps n | n == 1 = 1 | otherwise = steps(next n)+1
stepsn for several different values of n.
It all seems to work without any problem. But at the same time one can wonder:
numbersthat calculates the actual list of numbers generated in the game:
Load the function into GHCi and try:numbers :: Int -> [Int] numbers n | n==1 =  | otherwise = n : numbers(next n)
Study the function definition: When n=1 the result is the list . Otherwise we use the operator
numbers 10[10, 5, 16, 8, 4, 2, 1]
numbers 17[17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
:, named cons, which constructs a list from an element and a list by placing the element at the top of the list. The result of
nfollowed by the list
Now we have defined the function
numbers we don't need to
steps anymore because there is a function
in the prelude that calculates the length of a list.
length (numbers 10)7