Calculate how much study time remains, then change the inputs and predict the output. Use the same program to see when a value needs a type annotation or mut.
Install Topaz and complete First Program before starting this lesson.
Calculate the remaining time
Save this code as values-functions.tpz in your working folder.
function minutesLeft(total: int, spent: int) -> int {
total - spent
}
let topic = "Topaz basics"
let total: int = 45
let spent = 20
let mut sessions = 0
sessions = sessions + 1
print("{topic}: {minutesLeft(total, spent)} minutes left")
print("sessions: {sessions}")In that folder, check the file and run it.
topaz check values-functions.tpz
topaz run values-functions.tpzThe check succeeds with exit code 0. The program prints these two lines.
Topaz basics: 25 minutes left
sessions: 1Follow the calculation
minutesLeft(45, 20) returns 25, which appears in the first output line. The function receives the two numbers through its parameters, total and spent.
Each : int says that the parameter takes an integer. The -> int says that the function returns an integer. The final expression, total - spent, supplies that result. Use return to leave a function earlier. The checker checks returned values against the declared return type.
Choose types and allow reassignment
Topaz infers a type when it determines that type from the initial value. Here, topic is a string and spent is an int. Writing total: int states the type explicitly, even though 45 also makes it clear.
A binding gives a value a name. With let, you can use the name but cannot assign another value to it. With let mut, you can reassign it. The counter sessions starts at 0 and becomes 1 when the next line adds one.
| What you need | What to write |
|---|---|
| A local value whose initial value makes its type clear | let spent = 20 |
| A visible type for someone reading the declaration | let total: int = 45 |
| A counter that will be reassigned | let mut sessions = 0 |
| Named function inputs and a result type | (total: int, spent: int) -> int |
If the checker reports a type mismatch, compare the value with the type beside its name. Pass an integer such as 20 to minutesLeft, rather than the string "20".
Try this
Edit the initial values of total and spent to 60 and 15. Leave the counter code unchanged. Predict both output lines, then check and run the file again.
Answer
The first line becomes Topaz basics: 45 minutes left because 60 - 15 is 45. The second stays sessions: 1 because the counter still increases once.
Continue to the next lesson
You are ready when you can change the inputs and locate the subtraction and counter update that explain the output.
Continue to Data and Control to store several study tasks. For reference, see Types and Functions & Generics. You can return to generics when a later example needs them.