Returning from a Function Call
When a function returns, its caller resumes at a pending expression or statement and can use the delivered value.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Mark the suspended work
For total = 1 + next_score(), the caller waits for the function call before completing the addition. If the function returns six, the addition yields seven and assignment follows. This is visible in the evaluation order even when the called function is several lines long. An exception can abandon the pending work.
Distinguish early return from completion of a loop
A search function that returns at its first match ends the whole call. With entries A, B, C and a match at B, C is never examined. If the caller expects all matches, the loop should build a collection and return after it. State whether the function contract calls for one result or every result.[1][2]
Trace a value from the innermost call
In result = 2 + rate("west") * units, the rate call needs to finish before its result can participate in multiplication. If it returns four and units is three, multiplication gives twelve and the addition produces fourteen. Draw the caller with a blank slot for the pending call's value. When execution returns, fill that slot and continue the expression. See precedence and the expression tree for which operation receives that value.
If the call raises an exception, the multiplication is not performed and the outer assignment does not receive a new result from that expression. Earlier effects in the call can remain. A traceback identifies the suspended callers that were active at the failure.
Choose exactly which operation a return ends
A search helper can return from a loop when it reaches the first eligible item. That return exits the entire call, so instructions after the loop do not execute for a successful search. A break instead exits the nearest loop and can let the helper compute a message or perform another common step before returning.
Use three items, with the middle one eligible, and predict which items are visited and what output is emitted. Then construct a no-match case. If the caller expects every match, the contract calls for retaining a result collection rather than returning at the first. See first-match scans for the specific rule that makes the early return desirable.