Functional Programming -- Exercises 1 TDA452 & DIT142 | LP2 | HT2015 | [Home]

# Exercises for Week 1: Getting Started with Haskell

This document is designed as introduction to Haskell and the interactive Haskell interpreter GHCi. You are supposed to go through this document using a computer. It's meant to be pretty simple stuff - feel free to skip over some exercises.

Exercises after week 1 of the course work perfectly well with pencil and paper, and we set aside some time on Tuesday mornings (9-10 in EA before the lecture) where you can work on these and ask questions.

You are supposed to work through this document in an afternoon. The most important tasks are to answer questions that look like this: Example question.

The questions in the first part come with a suggested answer that you can see by clicking at the question mark at the left. Try to answer the questions yourself before looking!

## ghci as a simple calculator

ghci is an Haskell interpreter, i.e. it is a program that evaluates Haskell expressions.

You can start ghci by typing ghci in a terminal.
`candela04> ghci`
We will underline the text that you as user of ghci have to write. ghci's output will not be underlined.
When you start ghci you will see this welcome message:
```   ___         ___ _
/ _ \ /\  /\/ __(_)
/ /_\// /_/ / /  | |      GHC Interactive, version 6.4, for Haskell 98.
/ /_\\/ __  / /___| |      http://www.haskell.org/ghc/
\____/\/ /_/\____/|_|      Type :? for help.

Prelude>
```
Right 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 Prelude means. 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:
`Prelude> 4+5*634Prelude> `
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:
`Prelude> 4*(8-5)+315Prelude> 3.5/(3+4)*4.52.25Prelude> sin 1.571.0Prelude> ` The first of the expressions contains a multiplication-,  addition-,  and a subtraction operator. In which order are these operators applied? Which numbers are mulitplicated, added, and subtracted? What will the result be if we take away the parentheses in the first expression, i.e. 4*8-5+3 ? In which order are the operators applied in the second expression?
We don't always get a value as result when we give ghci an expression, it can be the case that our expression contains an error... Try:
```Prelude> 3+5*
:1:4: parse error (possibly incorrect indentation)
Prelude>
```
The first expression contains a syntax 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!

## More ghci commands

We use the :q command to finish a ghci session.
```Prelude> :q
Leaving GHCi.
candela04>
```
All ghci commands except evaluating an expressions start with a colon :
Restart ghci and try to answer the following questions by inspecting the welcome message. Which ghci commands are there?

## Two simple examples The sell rate for the English pound was 12.7775 SEK on the 20th of October 2008. How many  pounds did one get for 1000 SEK that day? In some countries people use the Fahrenheit temperature scale. 0° Celsius (C) corresponds to 32° Fahrenheit (F), and an increase of 5° C corresponds to an increase of 9° F. How many Fahrenheit degrees is 28° C?

## 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 the name pound.
• 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 kr as parameter.
• Express the result in terms of the parameters. In this case the result is: kr/12.7775 pound.
• Decide upon the type of the function. In this case:
`pounds:: Double -> Double`
• Write the complete Haskell function definition. In this case:
• `pounds :: Double -> Doublepounds kr = kr/12.7775`
Before we can use the definition we have to give it to ghci. Although it is possible to do this directly in ghci, it is more useful to learn how to do this in a seperate file, since this is what we have to do for larger programs.
1. Use an editor (for example xemacs or nedit) to write the function definition in a file. Do this, start xemacs with the command xemacs ex1.hs & in a terminal, and write the definition above. Save this to a file with name ex1.hs
2. Give ghci a command to load the file
```Prelude> :l ex1.hs
Compiling Main             ( ex1.hs, interpreted )
*Main> ```
We can now use the definition: Try:
```Main> pounds 100078.2626Main> pounds 12345966.151Main> pounds 12777510000.0Main>
``` Define a function that converts temperatures in ° C to ° F. Add this function to ex1.hs. Load the file and test your function. We will now introduce a new kind of error. What happens if one writes pount 10 (note the spelling error). What happens if one writes: pounds kr

## Comparison and more complex functions

Up 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 10 Kg.
We want to define the function that calculates the price.

Let's call this function price and the parameter v.
When v is at most 10, then the price is 3.50*v. If v is more than 10, the price is 35+3*(v-10) (check this!) which is equal to 5+3*v. So, we have:

price(v) = 3.5*v
, if v<=10
price(v) = 5+3*v, if v>10
How does one write this in Haskell? First, notice that ghci can compare numbers.Try:
`Main> 3 < 6TrueMain> 3.5 <= 3FalseMain> pounds 4000 > 3*100True`
The result of such a comparison is either True or False. Notice, that smaller than or equal to is written as <=. Now, we can write the definition of price as follows:
```price :: Double -> Doubleprice v   |v <= 10 = 3.5*v   |v > 10  = 5+3*v
```
The Boolean expressions between | and < are called guards. When this function is applied to a particular argument, ghci checks evaluates 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 False ghci gives an error message.

Load this function into ghci, and test the function price on different arguments. Change the last of the definitions to:
`   |v > 11  = 5+3*v`
What is the result of applying the function to 9.5, 10.5 respective 11.5? Change the function to:
`price v    |v <= 11 = 3.5*v   |v > 10  = 5+3*v`
What is the now result of applying the function to 9.5, 10.5 respective 11.5?
We can use the keyword otherwise as a guard that is always true. So, if otherwise is 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
``` The sale of potatoes has been so successful that the shop now can offer a price of 2.50 SEK/kilo for quantities exceeding 20 KG (with the same prices for other amounts). Change the function to to calculate the correct price.

Is 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.

`Main> price 7.526.25Main> price 1138.5Main> price (4+8)41.0Main>` Try to evaluate the last expression without parentheses. Can you explain the result?

## Functions with more than one argument

Functions 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: average.
• Input: Two floating point numbers.
Output: A floating point number giving the average of the two arguments.
• Names of the parameters: x and y.
• The result in terms of the parameters: (x+y)/2
• The type:
`average :: Double -> Double -> Double`
• The complete definition:
```average :: Double -> Double -> Double
average x y = (x+y)/2
```
Observe that when a function has multiple arguments the parameters are written after each other separated by spaces.
The same holds when the function is applied to parameters.
`Main> average 5 86.5Main> ` Define a function that gives the average of three numbers. Load in the function in ghci and test it.

## The Prelude

Some 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 arguments

Operators like *,-,+ are written infix, which  means that the operator should be in 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:
```Main> 5 `average` 44.5Main> 4 `max` (5 `max` 2)5Main> (+) 3 47Main>
```

## Integers.

The prelude provide the function div for integer division. Try:
`Prelude> div 17 53Prelude> div 34 84Prelude> div 5 90Prelude> 4 `div` 22Prelude> `
The function mod gives the remainder for integer division:
`Prelude> 17 `mod` 52Prelude> 34 `mod` 82Prelude> 5 `mod` 95Prelude> mod 4 20Prelude> ` What is 5 `mod` 0? Is 107139224 divisible by 11731? Define a function that given a year gives the number of days in that year. Used the simplified rule that year numbers divisible by four are leap years (years with 366 days).
You will have to use relational operator == which evaluates to True if 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.

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 a function next that given a number computes the next number in the sequence. Define the function next What is the length of the sequence for n = 6? We want to define a function steps that takes a number n as argument and calculates the length of the generated sequence. What is steps 20? And steps 3?
Guided by the previous exercise we observe that the function steps complies with:
`steps :: Int -> Intsteps n   |n == 1    = 1   |otherwise = steps(next n)+1`
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 calculate steps n for several different values of n.
It all seems to work without any problem. But at the same time one can wonder: Can you be sure that eventually you will reach the number 1 no matter what number you start with?
Finally, we define the function  numbers that calculates the actual list of numbers generated in the game:
`numbers :: Int -> [Int]numbers n     |n==1      =      |otherwise = n : numbers(next n)`
Load the function into ghci and try:
`Main> numbers 10[10, 5, 16, 8, 4, 2, 1]Main> numbers 17[17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]Main> numbers 1Main> `
Study the function definition: When n=1 the result is the list . Otherwise we use the operator : , 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 numbers n is n followed by the list numbers(next n).

Now we have defined the function numbers we don't need to define steps anymore because there is a function length in the prelude that calculates the length of a list.

`Try:Main> length [1,6,33,8,7,14]6Main> length (numbers 10)7Main> `