NCL 409: Associative Arrays
In the previous lesson, we searched an array to answer a question:
How old is Alice?
We didn't know Alice's index. Instead, we searched the Name field until we found her record, then read the Age field.
From outside that search, the relationship was much simpler:
"ALICE" → 29
We gave the program one value and got another value associated with it.
We can make that relationship the structure itself.
Keys and Values
An ordinary array identifies its elements by position:
index → value
An associative array identifies them using another value:
key → value
For our friends:
| Key | Value |
|---|---|
"NEMI" |
34 |
"ALICE" |
29 |
"BOB" |
41 |
"CHARLIE" |
32 |
The names are our keys.
The ages are our values.
Instead of asking for element 1, we can think in terms of asking for the value associated with "ALICE":
"ALICE" → 29
The physical position of Alice's entry no longer matters to whoever uses the collection.
An ordinary array identifies a value by its position. An associative array identifies a value by a key.
Unique Keys
A key identifies one entry.
This creates an important rule:
Each key must be unique.
Consider this collection:
| Key | Value |
|---|---|
"ALICE" |
29 |
"BOB" |
41 |
"ALICE" |
35 |
What does "ALICE" mean now?
"ALICE" → 29?
"ALICE" → 35?
The association is ambiguous.
Our associative array therefore allows each key to appear only once.
Values don't need to be unique:
| Key | Value |
|---|---|
"NEMI" |
34 |
"ALICE" |
29 |
"BOB" |
34 |
There's no ambiguity here.
"NEMI" → 34
"BOB" → 34
Different keys can be associated with the same value.
Getting a Value
Let's implement our associative array using memory we already know how to organize.
We'll reserve $100 as a length header and store key-value entries after it:
| Address | Value |
|---|---|
$100 |
4 |
$101 |
"NEMI" |
$102 |
34 |
$103 |
"ALICE" |
$104 |
29 |
$105 |
"BOB" |
$106 |
41 |
$107 |
"CHARLIE" |
$108 |
32 |
Each entry has a stride of 2:
| Offset | Field |
|---|---|
0 |
Key |
1 |
Value |
This should look familiar.
To get the value associated with "ALICE", we can use the search from the previous lesson.
For each entry:
current key == "ALICE"?
When the comparison succeeds, the associated value is one location later.
So:
"ALICE" → matching entry → 29
The implementation is still an array and a search.
The way we're using that implementation has changed.
The Position Doesn't Matter
Suppose we rearrange the entries:
| Index | Key | Value |
|---|---|---|
0 |
"BOB" |
41 |
1 |
"CHARLIE" |
32 |
2 |
"NEMI" |
34 |
3 |
"ALICE" |
29 |
Alice has moved from index 1 to index 3.
But:
"ALICE" → 29
hasn't changed.
The association is the same.
The numeric index exists because of the way we've chosen to store our entries, but it isn't how we identify them.
That's an important distinction:
The key is part of the structure's meaning. The index is part of our implementation.
Setting a Value
Suppose Alice has a birthday.
We want:
"ALICE" → 30
We must not simply append another entry:
| Key | Value |
|---|---|
"ALICE" |
29 |
"ALICE" |
30 |
That would violate our unique-key rule.
Instead, setting a value begins with a search.
If "ALICE" already exists, replace the value in that entry:
| Key | Before | After |
|---|---|---|
"ALICE" |
29 |
30 |
But suppose we set:
"DOUG" → 27
There is no "DOUG" entry to replace.
Now we append a new entry and increase the length:
| Key | Value |
|---|---|
"NEMI" |
34 |
"ALICE" |
30 |
"BOB" |
41 |
"CHARLIE" |
32 |
"DOUG" |
27 |
So setting a value has two possible outcomes:
| Search result | Action |
|---|---|
| Key found | Replace its value |
| Key not found | Add a new entry |
This is more than merely appending records.
Setting means updating the association if it already exists, or creating it if it doesn't.
Removing an Entry
Removing an association also begins by finding its key.
Suppose we remove:
"BOB"
Our associative array is implemented using a contiguous array, so removing Bob's entry leaves a gap.
We already know how to deal with that from NCL 406: Array Headers.
Shift the later entries toward the beginning and decrease the length.
Before:
| Index | Key | Value |
|---|---|---|
0 |
"NEMI" |
34 |
1 |
"ALICE" |
30 |
2 |
"BOB" |
41 |
3 |
"CHARLIE" |
32 |
4 |
"DOUG" |
27 |
After:
| Index | Key | Value |
|---|---|---|
0 |
"NEMI" |
34 |
1 |
"ALICE" |
30 |
2 |
"CHARLIE" |
32 |
3 |
"DOUG" |
27 |
Charlie and Doug now have different numeric indices.
Their associations haven't changed:
"CHARLIE" → 32
"DOUG" → 27
Again, position is an implementation detail.
Getting, Setting, and Removing
We can think of our structure as providing three basic operations:
| Operation | Meaning |
|---|---|
| Get | Find the value associated with a key |
| Set | Add or replace an association |
| Remove | Delete an association |
These aren't NCL instructions.
They're operations we've decided our data structure should provide.
Each one can be built from machinery we've already learned.
Getting uses searching.
Setting uses searching and possibly appending.
Removing uses searching and array deletion.
An associative array isn't new memory hardware. It's an agreement about how ordinary memory is organized and used.
Missing Keys
A get can fail.
If we ask for:
"FRED"
and there is no "FRED" entry, there is no associated value to return.
The structure needs some way to represent that result.
We could return a separate success value, use a sentinel, branch to different code, or choose some other convention.
What we shouldn't do is silently assume that a particular ordinary value means missing.
For example:
"FRED" → 0
is ambiguous if 0 could also be a perfectly valid value.
Absence is separate from value
A missing key and a key associated with 0, -1, or "" are not necessarily the same thing.
When designing an associative structure, decide explicitly how a failed lookup is represented.
The Structure and Its Implementation
Our associative array currently looks like this in memory:
[length][key][value][key][value][key][value]...
We find a key using the linear search from the previous lesson.
That's one way to implement an associative array.
It isn't the definition of one.
The important relationship is:
key → value
How we arrange memory and how we locate the key are separate decisions.
Do associative arrays always search every entry?
No.
Ours does because we've built it from tools we already understand: an array of key-value entries and a linear search.
That's a perfectly reasonable implementation for a small collection, but it gets increasingly expensive as the collection grows.
Other implementations use additional organization to locate keys much more quickly. Hash tables are one common example.
We won't build one here. The important distinction is that associative array describes how we use the collection, not how it must be arranged in memory.
Our version searches an array. Another implementation might do something much smarter underneath while presenting the same key-to-value relationship.
Associating Addresses
The value doesn't have to be the information we're ultimately interested in.
It can be an address.
Suppose our friends now have larger records containing several fields:
| Address | Name | Age | Score |
|---|---|---|---|
$180 |
"BOB" |
41 |
5100 |
$200 |
"NEMI" |
34 |
9000 |
$300 |
"ALICE" |
30 |
7200 |
Instead of copying all of that information into our associative array, we can associate each name with the address of its record:
| Key | Record address |
|---|---|
"NEMI" |
0x200 |
"ALICE" |
0x300 |
"BOB" |
0x180 |
Now:
"ALICE" → 0x300 → record
The associative array tells us where Alice's record lives.
Once we have 0x300, indirect addressing gives us access to the record itself.
The records don't need to be adjacent.
They don't need to appear in the same order as the associative entries.
And changing Alice's age or score doesn't require changing the association:
"ALICE" → 0x300
still points to the same record.
This is the same idea we encountered with linked structures: addresses are values too.
A structure can contain the data itself, or it can contain addresses to data stored somewhere else.
Structures Can Work Together
We've now used several different arrangements of memory.
An array calculates the location of an element from its index.
A linked list stores the location of the next record.
An associative array lets us find a value using a key.
And those ideas can be combined.
Our associative array contains addresses to records:
key → address → record
A record could contain an address to an array.
An array could contain addresses to linked records.
None of these structures require a new kind of memory.
They're different agreements about what the values in memory mean.
Is this starting to look like a database?
A little.
Databases build much larger systems around several ideas we've already seen: records made from fields, collections of records, searching by field values, and information that helps us find particular records.
A database might keep an index that associates some searchable value with the location of a record.
Conceptually, that can look remarkably familiar:
"ALICE" → record
Real database indexes can use much more sophisticated structures, especially when they need to search enormous collections efficiently.
But the basic problem should look familiar now: we have some information about a record, and we want to find the record without already knowing where it is.
Try It
We have this associative array:
| Index | Key | Value |
|---|---|---|
0 |
"RED" |
10 |
1 |
"GREEN" |
20 |
2 |
"BLUE" |
30 |
The length is stored in $100, and the entries begin at $101.
Each entry has a stride of 2.
#target contains a key and #value contains a new value.
Write the part of a set operation that runs after the search has finished.
Assume:
#indexcontains the matching index, or-1if the key wasn't found.- there is enough capacity for another entry.
- if the key is missing, append it to the end.
- leave the array with exactly one entry for
#target.
Show me one solution
First check whether the search found an existing entry:
BEQ :append #index -1
If it did, calculate the address of that entry's Value field:
MUL #address #index 2
ADD #address #address 0x102
MOVE [#address] #value
JUMP :done
If the key wasn't found, use the current length as the index of the new entry:
:append
MOVE #index $100
MUL #address #index 2
ADD #address #address 0x101
S.MOVE [#address] #target
INC #address
MOVE [#address] #value
INC $100
:done
An existing key has its value replaced.
A missing key gets one new entry appended to the array.
We've seen how a collection can identify values by keys instead of positions, and how that relationship can be implemented using structures and algorithms we already know.
In the next lesson, NCL 410: Multidimensional Arrays, we'll organize linear memory into structures with more than one dimension.