Functions Tutorial, Part 1¶
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:
fun indicates that what follows is a function.
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
Bool indicates that the function returns a Boolean
In sum, the first line says that the function
isOdd takes an
argument and returns a
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
False. Note that since we only accept
n, we know the remainder will be either
To call the function, you assign its result to a binding, as we have
y below. Pass the argument by including it within the
Because 7 is an odd number,
y will be bound to the value
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
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:
Download the answer key if you’d like to check your work.