Lesson contents

Combining a map and a list for a cache

A least-recently-used cache remembers a limited number of items. A lookup table finds a key and an ordered list records which key was used most recently.

Simple example

A two-place cache receives keys 1, 2, 1 and 3. Looking up 1 refreshes it. Print the evicted key, 2.

Start1 2 1 3
Result2
lesson.mojo
def main():
    var requests: List[Int] = [1, 2, 1, 3]
    var recent: List[Int] = [-1, -1]
    var i = 0
    while i < 4:
        var key = requests[i]
        if key != recent[0]:
            if (key != recent[1] and recent[1] != -1):
                print(recent[1])
            recent[1] = recent[0]
            recent[0] = key
        i += 1
Output
2
Advertisements

Everyday examples

Keep two books on a desk

You read A, then B, then A again. Which book leaves when C arrives?

StartA B A +C
ResultB

Reading A again makes it the more recent book. Remove B to make room.

Reuse a map tile

A phone already holds tile 7 and asks for 7 twice. How many cache entries should it use?

Start7 7
Result1

Refresh the existing entry. Adding a duplicate would waste one of the limited places.

Open a file after eviction

A one-place cache holds A. You open B, then reopen A. Where does the second A come from?

StartA B A
ResultA

Opening B removed A. Fetch A again from storage and replace B.

Cost and limits

A hash map of nodes and a doubly linked list allow average O(1) lookups, moves and evictions. A small array can demonstrate the rule with a slower scan.