Part 15

Working with examples

When you see an example definition like this

polynomial :: Double -> Double
polynomial x = x^2 - x - 1

you should usually play around with it. Start by running it. There are a couple of ways to do this.

If a definition fits on one line, you can just define it in GHCi:

Prelude> polynomial x = x^2 - x - 1
Prelude> polynomial 3.0
5.0

For a multi-line definition, you can either use ; to separate lines, or use the special :{ :} syntax to paste a block of code into GHCi:

Prelude> :{
Prelude| polynomial :: Double -> Double
Prelude| polynomial x = x^2 - x - 1
Prelude| :}
Prelude> polynomial 3.0
5.0

Finally, you can paste the code into a new or existing .hs file, and then :load it into GHCi. If the file has already been loaded, you can also use :reload.

-- first copy and paste the definition into Example.hs, then run GHCi
Prelude> :load Example.hs
[1 of 1] Compiling Main             ( Example.hs, interpreted )
Ok, one module loaded.
*Main> polynomial 3.0
5.0
-- now you can edit the definition
*Main> :reload
[1 of 1] Compiling Main             ( Example.hs, interpreted )
Ok, one module loaded.
*Main> polynomial 3
3.0

After you’ve run the example, try modifying it, or making another function that is similar but different. You learn programming by programming, not by reading! s

Arithmetic

There’s one thing in Haskell arithmetic that often trips up beginners, and that’s division.

In Haskell there are two division functions, the / operator and the div function. The div function does integer division:

Prelude> 7 `div` 2
3

The / operator performs the usual division:

Prelude> 7.0 / 2.0
3.5

However, you can only use div on whole number types like Int and Integer, and you can only use / on decimal types like Double. Here’s an example of what happens if you try to mix them up:

halve :: Int -> Int
halve x = x / 2

error:No instance for (Fractional Int) arising from a use of/’
    • In the expression: x / 2
        In an equation forhalve: halve x = x / 2

Just try to keep this in mind for now. We’ll get back to the difference between / and div, and what Num and Fractional mean when talking about type classes.

Exercises:

All exercises for this chapter can be found in Set1.

Remember that you can test your functions by using

stack ghci Set1.hs

So for example, after having made the function double in exercise 2, you can test your function by using

stack ghci Set1.hs
GHCi, version 9.2.8: https://www.haskell.org/ghc/  :? for help
[1 of 2] Compiling Mooc.Todo        ( Mooc/Todo.hs, interpreted )
[2 of 2] Compiling Set1             ( Set1.hs, interpreted )
Ok, two modules loaded.
ghci> double 2
4

Then, you can run the test by using

stack runhaskell Set1Test.hs

You should be able to make the following exercises now:

You have reached the end of this section! Continue to the next section:

You can check your current points from the blue blob in the bottom-right corner of the page.