Functions Tutorial, Part 1

You can download the source code for this tutorial here. Find the answer key here.

A Simple Function

We’ll start this tutorial by looking at a very basic function.

fun isOdd(n: Int) -> Bool:
  n % 2 == 1

y: isOdd(7)

Let’s zoom in on the first line:

fun isOdd(n: Int) -> Bool:

Here, fun indicates that what follows is a function. isOdd is the name of our function. Inside the parentheses, parameters are listed along with their types. n is a parameter of type Int, so it’s an integer. The -> glyph means “returns,” so Bool indicates that the function returns a Boolean value.

In sum, the first line says that the function isOdd takes an Int argument and returns a Bool value.

Let’s look at the second line, or the body of the function:

n % 2 == 1

The body of the function is where the work happens. Essentially, this function uses the modulus operator to determine whether an argument is an odd number. If the parameter n has a remainder when divided by 2, then the result of the function is the Boolean value True. If the remainder is zero, then the number is even so the function returns the Boolean value False. Note that since we only accept Int values for n, we know the remainder will be either 0 or 1.

To call the function, you assign its result to a binding, as we have with y below. Pass the argument by including it within the parentheses.

y: isOdd(7)

Because 7 is an odd number, y will be bound to the value True.

Exercise 1

Ready for your first exercise? Below is a function, but there’s something wrong with it. Find the mistake and fix it, so that the module compiles.

When fixed, the doubleNumber function doubles a given integer. It takes an integer as a parameter and returns another integer, twice the original value.

fun doubleNumber(num: Int) Int:
  num * 2

Hint: If you try to compile the module as is, the compiler will give you a tip about what’s wrong.

You can download the file here. Compile it by executing the following:

lwc FunctionTutorial1.lw

Download the answer key if you’d like to check your work.