This exercise will be an introduction to working with the Haskell tools. For this course, we will be using the Glasgow Haskell Compiler (but other Haskell implementations should be usable as well).
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.
-
Start by getting GHC installed (or going to CSIL). We will start by using the GHC interactive environment. (Type
ghciat 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.hscontaining 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
-
Save your
exer1.hs. You can test it in GHCi like this:Prelude> :l exer1.hs *Main> det 1 4 2 8 *Main> quadsol1 1 4 2 -3.414213562373095 *Main> quadsol2 1 4 2 -0.5857864376269049
-
Add to your
exer1.hsa functionsquarethat takes one number as an argument and returns the square that value. (So,square 4should return 16.)In GHCi, you can reload your
exer1.hsand test it like this:*Main> :r Ok, modules loaded: Main. *Main> square 8 64
-
Add another function to your
exer1.hscalledthirdthat 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> third [7,8,9,10,11,12] 9 *Main> third [1,2] *** Exception…
-
Finally, in your
exer1.hs, write a functionhailstone nthat find the next element in a hailstone sequence. That is, for evenn, it should returnn/2; for oddn, it should return 3n+ 1. (Hint: the Haskelldivfunction does integer division; the/always returns a Float, which is not what you want.)> hailstone 14 7 > hailstone 31 94
Submit your work for this exercise in CourSys. [You aren't submitting anything for parts 2 and 4: we'll trust that you have done them.]