NCL 510: Callbacks
In the last two lessons, we've learned how to store execution destinations in memory and select which subroutine to call at runtime.
In NCL 508: Jump Tables, we selected handlers using numbers.
In NCL 509: Command Dispatch, we selected handlers using strings.
In both cases, the program found an execution destination and called it.
But there's another possibility.
What if we passed an execution destination to a subroutine, and let that subroutine decide when to call it?
We already know how to pass integers as arguments. And an execution destination is an integer.
Let's put those ideas together.
A Search with a Problem
Back in NCL 408: Linear Search, we learned how to search an array by examining its elements one at a time.
Suppose we have this array:
| Index | Value |
|---|---|
| 0 | 13 |
| 1 | 7 |
| 2 | 4 |
| 3 | 21 |
| 4 | 8 |
| 5 | -9 |
| 6 | 16 |
| 7 | 3 |
We'll store it beginning at $300, with a length header:
MOVE $300 8
MOVE $301 13
MOVE $302 7
MOVE $303 4
MOVE $304 21
MOVE $305 8
MOVE $306 -9
MOVE $307 16
MOVE $308 3
Suppose we want to find the first even number.
We can examine each element, calculate its remainder when divided by two, and stop when that remainder is zero.
The answer would be index 2, containing 4.
Now suppose we want to find the first negative number.
The answer would be index 5, containing -9.
The two searches have almost everything in common.
Both begin at the first element, examine values in order, and return the index of the first match.
Only the condition changes.
We could write two separate search routines, but we'd be duplicating most of their instructions.
Or we could add a mode to one search routine:
0 = Find even numbers
1 = Find negative numbers
That would work, but every new kind of search would require another condition inside the search routine.
Can we separate how we search from what we're searching for?
Asking Another Subroutine
Let's divide the work.
The search routine will handle the array:
- Start at index zero.
- Retrieve the current element.
- Ask whether it matches.
- Return the index if it does.
- Otherwise, continue to the next element.
Another subroutine will decide whether an individual value matches.
For example, we might have:
:is_even
:is_negative
:is_positive
Each of these subroutines answers a question about one integer.
A subroutine that tests a condition and returns a true-or-false result is called a predicate.
We'll give every predicate the same interface.
| Direction | Value | Type |
|---|---|---|
| Argument | Value to test | Integer |
| Result | Whether it matches | Integer |
A result of 0 means false. A nonzero result means true.
Let's write our first predicate.
Testing for Even Numbers
An integer is even when dividing it by two leaves a remainder of zero.
We can use MOD to calculate that remainder.
#value $000
#remainder $001
:is_even
POP #value
MOD #remainder #value 2
BEQ :even #remainder 0
PUSH 0
RET
:even
PUSH 1
RET
The caller supplies one integer:
PUSH 8
CALL :is_even
The predicate removes that argument, checks it, and pushes its result.
The caller can retrieve it:
POP #result
For 8, the result is 1.
For 7, the result is 0.
Notice what :is_even doesn't do.
It doesn't search an array. It doesn't calculate an index. It doesn't know where the value came from.
It only decides whether one value is even.
That's all our search needs to ask.
Passing a Predicate
Normally, we call a subroutine by writing its destination directly:
CALL :is_even
But a label represents an integer execution destination.
We can push that destination onto the value stack:
PUSH :is_even
This doesn't execute :is_even.
It pushes its destination as an ordinary integer value.
We can then call our search routine:
PUSH :is_even
CALL :find_first
When :find_first begins, it can pop the supplied destination into memory:
#predicate $010
:find_first
POP #predicate
Now $010 contains the execution destination of :is_even.
To call it, we can write:
CALL #predicate
The processor reads the destination stored at $010 and calls it.
We haven't written :is_even into the CALL instruction.
The destination comes from the caller.
This is a callback: a subroutine supplied to another subroutine, which can invoke it as part of its own work.
The caller decides which predicate to supply.
The search routine decides when to invoke it.
One level of indirection
When #predicate is defined as $010, CALL #predicate uses the execution destination stored at $010.
CALL [$010] would mean something different: it would treat the value in $010 as another memory address, then read the execution destination from there.
Our search receives the destination itself, so CALL #predicate is what we need.
Why 'callback'?
The name comes from the idea that one part of a program supplies a routine for another part to call back into.
Callbacks are common in searching, sorting, user interfaces, and many other kinds of software.
They don't require a special callback instruction.
In NCL, ordinary argument passing and CALL are enough.
The Search Interface
Let's define what :find_first expects.
For now, it will always search the headed array beginning at $300.
The caller supplies one predicate destination.
The search returns the index of the first matching element, or -1 if no element matches.
| Direction | Value | Type |
|---|---|---|
| Argument | Predicate destination | Integer |
| Result | First matching index, or -1 |
Integer |
The predicate has its own interface:
| Direction | Value | Type |
|---|---|---|
| Argument | Array element | Integer |
| Result | Match result | Integer |
These are two separate agreements.
The caller agrees with :find_first about how to request a search.
:find_first agrees with the predicate about how to test an element.
As long as those interfaces are respected, neither needs to know how the other is implemented.
Building the Search
We'll use Scratch memory for the search's working values.
#predicate $010
#index $011
#address $012
#element [$012]
#length $013
#matches $014
Notice the two aliases involving $012.
#address refers to the memory location holding the current element's address.
#element is the complete indirect operand [$012], which retrieves the value stored at that address.
We begin by receiving the predicate destination:
:find_first
POP #predicate
Then initialize the search:
MOVE #index 0
MOVE #length [$300]
The array's length is stored at $300, and its first element is at $301.
At the beginning of each iteration, we'll check whether we've reached the end:
:search_next
BGE :not_found #index #length
If there are still elements to examine, calculate the address of the current one:
ADD #address 0x301 #index
For index 0, this produces 0x301.
For index 1, it produces 0x302.
And so on.
We can retrieve the current value using #element.
But before we call the predicate, there's something important to consider.
Protecting Our Progress
The search uses Scratch memory.
The predicate will probably use Scratch memory too.
And as we learned in NCL 504: Scratch and Preserved State, a caller cannot assume its Scratch values will survive a subroutine call.
If we simply write:
PUSH #element
CALL #predicate
the predicate might overwrite #index, #length, or even #predicate.
Our search could lose its place.
Fortunately, we already know how to protect values across a call.
We can push them onto the value stack.
PUSH #predicate
PUSH #index
PUSH #length
Now those values are safe.
Next, we push the predicate's argument:
PUSH #element
The stack contains, from bottom to top:
| Position | Value |
|---|---|
| Bottom | Predicate destination |
| Current index | |
| Array length | |
| Top | Current element |
The predicate sees its argument at the top of the stack, exactly where it expects it.
We can call it:
CALL #predicate
The predicate removes the element and pushes its result.
We retrieve that result first:
POP #matches
Then restore the search's saved values in reverse order:
POP #length
POP #index
POP #predicate
Our search can now continue with its original state intact.
The complete callback invocation looks like this:
-- Preserve our progress.
PUSH #predicate
PUSH #index
PUSH #length
-- Ask the predicate about this element.
PUSH #element
CALL #predicate
POP #matches
-- Restore our progress.
POP #length
POP #index
POP #predicate
We don't need to preserve #address, because we'll calculate it again on the next iteration.
We also don't need to preserve the old value of #matches, because the callback's result replaces it.
Two uses of the same stack
The saved search state sits below the predicate's argument.
The predicate consumes its argument and returns one result, leaving the saved values untouched.
Once the search removes the result, it can restore its state.
This is ordinary value-stack argument passing, combined with the preservation techniques we've already learned.
Finishing the Search
Once the predicate returns, #matches contains its answer.
If the result is nonzero, we've found a match:
BNE :found #matches 0
Otherwise, advance to the next element:
INC #index
JUMP :search_next
If we find a match, return its index:
:found
PUSH #index
RET
If we reach the end of the array without finding one, return -1:
:not_found
PUSH -1
RET
That's our reusable search.
The Complete find_first
Here's the whole subroutine:
#predicate $010
#index $011
#address $012
#element [$012]
#length $013
#matches $014
:find_first
POP #predicate
MOVE #index 0
MOVE #length [$300]
:search_next
BGE :not_found #index #length
-- Locate the current element.
ADD #address 0x301 #index
-- Preserve state across the callback.
PUSH #predicate
PUSH #index
PUSH #length
-- Test the element.
PUSH #element
CALL #predicate
POP #matches
-- Restore state.
POP #length
POP #index
POP #predicate
-- Stop if the predicate accepted it.
BNE :found #matches 0
INC #index
JUMP :search_next
:found
PUSH #index
RET
:not_found
PUSH -1
RET
The search knows how to examine an array and when to stop.
It doesn't know what makes an element match.
That decision belongs entirely to the supplied predicate.
Using the Search
Let's return to our array:
| Index | Value |
|---|---|
| 0 | 13 |
| 1 | 7 |
| 2 | 4 |
| 3 | 21 |
| 4 | 8 |
| 5 | -9 |
| 6 | 16 |
| 7 | 3 |
To find the first even number:
PUSH :is_even
CALL :find_first
POP #result
The search examines the values in order.
| Index | Value | Predicate result |
|---|---|---|
| 0 | 13 | 0 |
| 1 | 7 | 0 |
| 2 | 4 | 1 |
The first match is at index 2.
So :find_first returns 2.
Now let's search for something else.
A Different Predicate
We'll write another predicate that recognizes negative integers.
#value $000
:is_negative
POP #value
BLT :negative #value 0
PUSH 0
RET
:negative
PUSH 1
RET
It follows exactly the same interface as :is_even.
One integer argument.
One integer result.
We can pass it to the same search routine:
PUSH :is_negative
CALL :find_first
POP #result
This time, the search examines:
| Index | Value | Predicate result |
|---|---|---|
| 0 | 13 | 0 |
| 1 | 7 | 0 |
| 2 | 4 | 0 |
| 3 | 21 | 0 |
| 4 | 8 | 0 |
| 5 | -9 | 1 |
The first negative value is at index 5.
So the search returns 5.
We haven't changed a single instruction inside :find_first.
We've changed what it looks for by changing the subroutine we pass to it.
The search controls the procedure. The predicate supplies the condition.
Selecting a Callback from a Table
We don't have to write the predicate destination directly into PUSH.
In 508, we learned how to store execution destinations in a table.
Let's make a small predicate table:
MOVE $200 :is_even
MOVE $201 :is_negative
Now suppose $100 contains the memory address of the selected table entry:
MOVE $100 0x201
We can retrieve that entry's value using indirect addressing:
PUSH [$100]
This pushes the execution destination stored at $201, which is :is_negative.
We can pass it to the search:
PUSH [$100]
CALL :find_first
POP #result
Notice the distinction.
PUSH [$100] follows a memory address to retrieve the selected predicate destination.
Inside :find_first, the destination is stored directly in #predicate, so the callback is invoked with:
CALL #predicate
The caller selects the callback.
The search receives it.
The search doesn't need to know about the table or how the selection was made.
Putting It Together
Here's a complete program that searches the same array using two different predicates.
The first search passes its predicate directly.
The second selects its predicate through a table.
-- Predicate working memory.
#value $000
#remainder $001
-- Search working memory.
#predicate $010
#index $011
#address $012
#element [$012]
#length $013
#matches $014
-- Result.
#result $020
-- Initialize the array.
MOVE $300 8
MOVE $301 13
MOVE $302 7
MOVE $303 4
MOVE $304 21
MOVE $305 8
MOVE $306 -9
MOVE $307 16
MOVE $308 3
-- Build the predicate table.
MOVE $200 :is_even
MOVE $201 :is_negative
-- Find the first even number.
PUSH :is_even
CALL :find_first
POP #result
D.TXT "FIRST EVEN: "
D.TXT #result
D.TXT "\r\n"
-- Select the negative predicate.
MOVE $100 0x201
PUSH [$100]
CALL :find_first
POP #result
D.TXT "FIRST NEGATIVE: "
D.TXT #result
D.BLT
JUMP :end
-- Search using a supplied predicate.
:find_first
POP #predicate
MOVE #index 0
MOVE #length [$300]
:search_next
BGE :not_found #index #length
ADD #address 0x301 #index
PUSH #predicate
PUSH #index
PUSH #length
PUSH #element
CALL #predicate
POP #matches
POP #length
POP #index
POP #predicate
BNE :found #matches 0
INC #index
JUMP :search_next
:found
PUSH #index
RET
:not_found
PUSH -1
RET
-- Predicate: even numbers.
:is_even
POP #value
MOD #remainder #value 2
BEQ :even #remainder 0
PUSH 0
RET
:even
PUSH 1
RET
-- Predicate: negative numbers.
:is_negative
POP #value
BLT :negative #value 0
PUSH 0
RET
:negative
PUSH 1
RET
:end
The display should show:
FIRST EVEN: 2
FIRST NEGATIVE: 5
Both results came from the same search routine.
The search didn't need a mode, a list of conditions, or a branch for each predicate.
It only needed an interface for asking whether an element matched.
Beyond Searching
We've used callbacks to decide whether an array element matches a condition.
But the same technique works whenever one subroutine needs another to supply part of its behavior.
A sorting routine could receive a comparison subroutine that decides which of two values comes first.
A drawing routine could receive a subroutine that chooses which character to place at each position.
A numerical routine could receive a calculation to perform repeatedly.
The pattern is the same:
- One subroutine controls the overall procedure.
- Its caller supplies another subroutine's execution destination.
- The receiving subroutine invokes that callback through an agreed interface.
- The callback returns a result that influences what happens next.
The callback doesn't need to know how the overall procedure works.
The receiving subroutine doesn't need to know how the callback calculates its result.
They only need to agree on the interface.
Higher-order procedures
A routine that accepts another routine as an argument is often called a higher-order procedure or higher-order function.
The idea appears in many programming languages, but it doesn't require special language features.
In NCL, execution destinations are ordinary integer values. We can store them, pass them, and use them with CALL.
Try It
Add a third predicate called :is_positive.
It should return 1 when its argument is greater than zero, and 0 otherwise.
Then add it to the predicate table:
MOVE $202 :is_positive
Select it through the table and use it with :find_first.
Don't modify the search routine.
With our example array, what index should it return?
Then change the array so that every element is zero or negative.
What should happen when the predicate never finds a match?
Use the existing interface
Your new predicate receives one integer through the value stack and returns one integer.
It should follow the same structure as :is_negative, but test the opposite comparison.
Testing the condition
A positive number is greater than zero.
Use BGT to branch to the matching case.
Remember that zero is neither positive nor negative.
Show me one solution
:is_positive
POP #value
BGT :positive #value 0
PUSH 0
RET
:positive
PUSH 1
RET
Add it to the table:
MOVE $202 :is_positive
Then select it:
MOVE $100 0x202
PUSH [$100]
CALL :find_first
POP #result
With our example array, the first positive value is 13, at index 0.
If no element is positive, :find_first returns -1.
In the 500-level, we've learned how to build programs from cooperating subroutines.
We examined the call stack, passed arguments and results through the value stack, defined interfaces, distinguished Scratch from preserved state, and used stack frames to keep subroutine invocations independent.
We built handlers, selected execution destinations using jump tables, and dispatched commands by name.
In this lesson, we combined those ideas to build a search routine that accepts another subroutine as an argument.
The search knows how to examine an array. The predicate knows what makes an element match.
By passing a different predicate, we can change the behavior of the search without changing its implementation.
A subroutine isn't only something we can call. Its execution destination is also a value we can store, select, and pass to another subroutine.
Ready to continue? In the next lesson, NCL 601: The Cost of Code, we'll begin exploring what makes one implementation more efficient than another.
Want to try one yourself first? The 500-Level Challenge will ask you to put the techniques from this level together.