07Functions
Results
Functions that work out a value and give it back.
The functions so far do something, such as printing. A lot of functions instead work out a value and hand it back to the caller: the area of a rectangle, the larger of two numbers. The value handed back is the function's result.
Expected output
၄၉
Two things change compared with a function that has no result:
| Where | No result | With a result |
|---|---|---|
| header | အောက်ပါတို့ကို လုပ်ဆောင်မည်။ ("will do the following") | အောက်ပါတို့ကို လုပ်ဆောင်ကာ <kind> ရလဒ် ကို ပြန်ပေးမည်။ ("doing the following, will return a kind result") |
| call | ... လုပ်ဆောင်ပါ။ ("run it") | ... လုပ်ဆောင်သော ရလဒ် ("the result of running it"), a value |
Returning the result
There are two options for giving back the result.
Return it. <value> ကို ရလဒ်အဖြစ် ပြန်ပေးပါ။ ("give back value as the result") ends the
function at once.
Set ရလဒ်. A function with a result has a built-in variable named ရလဒ်
("result") of the result's kind. It starts at the kind's default. Whatever it holds when
the function reaches its end is returned.
Expected output
၁၂
၁၀
Using a result
A call with လုပ်ဆောင်သော ရလဒ် is a value. Use it wherever a value fits: print it, store
it, pass it to another function, or use it in a sum:
Expected output
၉
၂၅
၁၆
Notice the parentheses in the sum. A statement that begins with လုပ်ဆောင်ချက် is read
as a call statement, so a sum that starts with a call needs the call in parentheses.
A call later in the sum, or a call on its own, needs none.
To discard a result, call the function as a statement with လုပ်ဆောင်ပါ။.
Results of other kinds
A result can be of whatever kind the function needs. This one gives back true or false:
Expected output
ပြတ်သည်
Mistakes
A function without a result has nothing to use as a value:
Expected error
error[ZK0315]: function "ပြ" returns nothing and cannot be used as a value
A function with a result must give a value back whenever it returns:
Expected error
error[ZK0313]: function "တစ်" returns isize, but no value is returned
Hands on
- Write a function that returns the smallest of three numbers.
- Write a function that returns true for multiples of 4 that are not multiples of 100, and also for multiples of 400. This is the leap rule of the Gregorian calendar.
Next: Recursion.