Part 15

The Structure of a Haskell Program

Here’s a simple Haskell program that does some arithmetic and prints some values.

module Gold where

-- The golden ratio
phi :: Double
phi = (sqrt 5 + 1) / 2

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

f x = polynomial (polynomial x)

main = do
    print (polynomial phi)
    print (f phi)
If you put this in a file called Gold.hs and run it with (for example) stack runhaskell Gold.hs, you should see this output
Sample output
0.0 -1.0

Let’s walk through the file.

module Gold where

There is one Haskell module per source file. A module consists of definitions.

-- The golden ratio

This is a comment. Comments are not part of the actual program, but text for human readers of the program. It is similar to using # comment in python.

phi :: Double
phi = (sqrt 5 + 1) / 2

This is a definition of the constant phi, with an accompanying type annotation (also known as a type signature) phi :: Double. The type annotation means that phi has type Double. The line with a equals sign (=) is called an equation. The left hand side of the = is the expression we are defining, and the right hand side of the = is the definition.

In general a definition (of a function or constant) consists of an optional type annotation and one or more equations

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

This is the definition of a function called polynomial. It has a type annotation and an equation. Note how an equation for a function differs from the equation of a constant by the presence of a parameter x left of the = sign. Note also that ^ is the power operator in Haskell, not bitwise xor like in many other languages.

f x = polynomial (polynomial x)

This is the definition of a function called f. Note the lack of type annotation. What is the type of f?

main = do
    print (polynomial phi)
    print (f phi)

This is a description of what happens when you run the program.

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.