Skip to content
UoL CS Notes

Lecture 3-2

COMP105 Lectures

Defining Custom Functions

Functions are defined as such:

[functionName][arguments][=][body]

Functions and arguments must start with small letters as only types use capitals.

They can be written into a file and loaded into GHCI or compiled for use in a program. An example of a simple function:

addTwo x = x + 2
twoInAddTwo x y = x + y + 2

Additional functions are available in the slides.

Loading Functions

  • To load a functions from a file run GHCI on the file. ghci functions.hs
  • To reload the current file run :reload in GHCI.
  • To load in a file run :load and the file-path.

Comments

Single line comments can be written -- like this

Multi-line comments can be written:

{- Like
   this-}

Compilation

Instead of running code in the interpreter you can compile it using GHC. To print the output to the StdOut you can use the two functions putStrln(show()) to convert the output to a string and print that to the StdOut.

This is part of the IO function-set and won’t be used again for a while.

Exercises

  1.  double x = 2 * x
    
  2.  pythagoras a b  = sqrt (a ** 2 + b ** 2)
    
    • Must use the float exponentiation operator to allow for floats as a or b.
  3.  maxFour a b c d = max (max a b) (max c d)`