# Exercise 1

This exercise will be an introduction to working with the Haskell tools. For this course, we will be using the Glasgow Haskell Compiler. You can download it from their web site; it is installed in CSIL Linux; or install the Ubuntu package ghc.

Some links to the GHC software have been provided. You will also find GHC on the CSIL Linux computers. The Haskell tutorials and references on the same page may be helpful as well.

## Getting Started with GHCi

Start by getting GHC installed (or going to CSIL). We will start by using the GHC interactive environment. (Type ghci at the Linux prompt to start it.) Once GHCi is started, you'll see a prompt like this:

Prelude>


You can start experimenting with Haskell at this prompt. Try typing some expressions at this prompt and look at the results. Some example things to try:

9 * 4
1 + 2 * 3
1+1 == 2
2^300
sum [1,2,3,4,5]
[1,2,3] ++ [4,5]
take 3 [5,6,7,8,9,10]
div 15 3
15 div 3
5 + 6
(+) 5 6


In your favourite text editor, create a file exer1.hs containing the following three function definitions (that calculate the discriminant and two solutions to a quadratic formula):

det a b c = b^2 - 4*a*c
quadsol1 a b c = (-b - sqrt (det a b c))/2*a
quadsol2 a b c = (-b + sqrt (det a b c))/2*a


You can test it in GHCi like this:

Prelude> :l exer1.hs
*Main> det 1 4 2
8
-3.414213562373095
-0.5857864376269049


Add another function to your exer1.hs called third_a that returns the third element of a list. It should behave like this: (including no need to check for the error if there is no third element)

*Main> :r
*Main> third_a [7,8,9,10,11,12]
9
*Main> third_a [1,2]
*** Exception…


The function third_a must use the built-in list indexing operator.

Write another implementation of the same logic, third_b that uses pattern matching to get to the third element. It should behave identically to third_a. (The exception might be different, but should occur in the same cases.)

## Hailstone Function

Finally, in your exer1.hs, write a function hailstone n that find the next element in the hailstone sequence. That is, for even n, it should return n/2; for odd n, it should return 3n+1. (Hint: the Haskell div function does integer division; the / always returns a Float, which is not what you want.)

*Main> hailstone 14
7
*Main> hailstone 31
94


You must not use an if expression (which isn't very Haskell-ish). Use a guarded expression.

## Submitting

Submit your files through CourSys for Exercise 1.

Updated Sat Aug. 25 2018, 11:27 by ggbaker.