User-defined types
INTEGER holds a number and STRING holds text, but a lantern in a hire shop is an ID, a wattage and a status all at once. A user-defined type lets the programmer design a type for data like that, then declare variables of that type.
One lantern, three fields, each with its own type:
Build the type the application needs
Tavren, a lantern hire shop, needs a count, a status with exactly three values, and each lantern’s ID, wattage and status kept together. A record groups related fields like those under one identifier; INTEGER alone cannot express the combination.
| Need | Type choice | Why it fits |
|---|---|---|
| A count of lanterns | Built-in INTEGER | The language already supplies whole-number values and arithmetic. |
| Exactly three named states | Enumerated LanternStatus | The definition lists the complete allowed values. |
| One lantern’s related details | Composite LanternRecord | Each named field has its own suitable type. |
A type definition is reusable
- Define LanternRecord once, then use it for one lantern, an array element or a file record.
- The name describes the data and makes declarations easier to read.
- A type definition describes the values a variable may hold; a declaration creates the variable.
1 A lantern’s colour must be one of Red, Amber or Green. Which kind of type fits?
2 A program keeps a customer’s name, phone number and number of hires together. Which kind of type fits?
3 What is the difference between a type definition and a declaration?
- 1an enumerated type: it lists the complete set of allowed values
- 2a record (composite) type: related fields of different types under one identifier
- 3a type definition describes the values; a declaration creates a variable of that type
Enumerated and pointer types
A lantern is available, on loan or in repair, and never anything else. An enumerated type restricts a value to a fixed list like that. Sometimes a program needs to say where a value is kept rather than what it is: a pointer type stores a reference to a memory location holding a value of a specified type.
TYPE LanternStatus = (Available, OnLoan, Repair) DECLARE CurrentStatus : LanternStatus
CurrentStatus ← Availableselects one listed value.- The values are unique, the list is complete and their order is fixed by the declaration.
- Available is an enumerated value, not the string "Available": the declaration has no quotation marks around it.
A pointer answers a different question: not what a value is, but where it is kept.
TYPE WattRef = ^INTEGER DECLARE WattPointer : WattRef
Follow the arrow: the pointer holds an address, and the box at that address holds the value.
Address and value are different
- 1If
Wattageis an INTEGER with value 6,WattPointer ← ^Wattagestores its address: the leading caret obtains the address. - 2
WattPointer^uses a trailing caret to dereference it and read 6. - 3If Wattage becomes 9 at the same location, dereferencing now reads 9.
| Expression | Meaning |
|---|---|
WattPointer | Reference to location 420 in this memory picture. |
WattPointer^ | The INTEGER value stored at that location. |
CurrentStatus | One of Available, OnLoan or Repair; no address is involved. |
1 TYPE Day = (Mon, Tue, Wed). Is "Mon", with quotation marks, a value of type Day?
2 WattPointer holds address 420 and location 420 now stores 12. What does WattPointer^ give?
3 In the same memory, what does WattPointer itself hold?
- 1no: Mon is an enumerated value; "Mon" is a string
- 212, the value at the location
- 3420, the address
Sets, records and objects
Two counters each pick out some lanterns. To ask which lanterns both chose, you need a type that records which lanterns belong, not their order. Choose the structure by what one value must represent: membership, related fields, or state with operations.
A set stores each member once
TYPE LanternIDs = SET OF INTEGER DEFINE CounterA (31, 8, 22) : LanternIDs DEFINE CounterB (8, 14) : LanternIDs
Draw the two sets as circles: an ID in the overlap was picked at both counters.
Read each operation off the circles:
| Set operation | Result | Meaning at the counters |
|---|---|---|
| Intersection A ∩ B | {8} | ID 8 appears in both selections. |
| Union A ∪ B | {8, 14, 22, 31} | Every selected ID, once each. |
| 22 ∈ A | TRUE | Membership: ID 22 is in CounterA. |
- All members have the declared element type.
- A set is unordered and has no duplicates: adding 8 again to A leaves three members. There is no “second member” to retrieve by position.
- Members may be added or removed; an enumeration instead defines its complete list of possible values.
An object holds state and offers methods
A record only holds data. A lantern can also be hired, and an object keeps that action with the data it changes.
class Lantern: def __init__(self, ID): self.ID = ID self.Status = "available" def Hire(self): if self.Status == "available": self.Status = "on-loan" a = Lantern(31) b = Lantern(8) a.Hire() print(a.Status, b.Status)
The program makes two objects from one class, then hires only a:
The class defines attributes and methods. Objects a and b are separate instances. Hiring a changes only its state. A record groups fields; use a class when the state and its permitted operations belong together.
1 CounterC holds 8 and 19. Give CounterA ∩ CounterC.
2 Give CounterA ∪ CounterC.
3 After the program above, b.Hire() also runs. What does print(a.Status, b.Status) show now?
- 1{8}
- 2{8, 19, 22, 31}
- 3on-loan on-loan
Designing a record type
A wattage of 7 or a status of “lost” would break the program later, so start from what each field means and which values are valid. Then define the record type, declare a record variable and assign every field before using it.
For stored Tavren records, ID is a whole-number identifier, Wattage is 6, 9 or 12, and Status is the text available, on-loan or repair. The text form makes the file format explicit; a runtime model may instead use LanternStatus for that field.
TYPE LanternRecord DECLARE ID : INTEGER DECLARE Wattage : INTEGER DECLARE Status : STRING ENDTYPE DECLARE Item, Copy : LanternRecord DECLARE Stock : ARRAY[0:5] OF LanternRecord Item.ID ← 31 Item.Wattage ← 6 Item.Status ← "available" Copy ← Item Copy.Status ← "on-loan" Stock[0] ← Item OUTPUT Stock[0].ID, " ", Stock[0].Status OUTPUT Copy.ID, " ", Copy.Status
Copy a record and select its fields
Follow the program to its end: three record variables, and only one field differs.
Each statement, and what it does to those records:
| Operation | Result |
|---|---|
Copy ← Item | All three fields are copied as one LanternRecord value. |
Copy.Status ← "on-loan" | Only Copy changes; Item remains available. |
Stock[0].ID | Select record 0, then its ID field: 31. |
- The record has a fixed set of related fields, which may have different types.
- An array of records stores many complete lantern values.
- A file key identifies a record for this application; a field’s name or position alone does not make its values unique.
1 Write the statement that sets the Wattage of Stock[2] to 9.
2 After the program above, Item.Wattage ← 12 runs. What is Copy.Wattage?
3 In Stock[0].ID, what does Stock[0] select, and what does .ID select?
- 1
Stock[2].Wattage ← 9 - 26: Copy holds its own copy of the fields
- 3
Stock[0]selects one record in the array;.IDselects one field of that record
Serial and sequential files
A file is only useful if the program can find a record in it again. Two choices decide how. File organisation describes how records are arranged; file access describes how a program reaches them. Keep them apart: the stored order is not the reading method.
The same six lanterns stored two ways. Follow the arrows: that is the order a program reads them.
What sets each order, and where Tavren uses it:
| Organisation | Stored order | Tavren use |
|---|---|---|
| Serial | New records are appended in arrival/time order. There is no ID ordering. | A log of lanterns received at a counter. |
| Sequential | Records are stored in a stated order using a key field; here, ascending ID. | An ID-ordered stock list for a complete daily check. |
Sequential access reads one record after another
Order pays off when you search. Follow each search one record at a time, and be able to say when it stops.
| Record | Test | |
|---|---|---|
| read 1 | 31 | not 8: read on |
| not 8: read on | ||
| read 2 | 14 | not 8: read on |
| not 8: read on | ||
| read 3 | 27 | not 8: read on |
| not 8: read on | ||
| read 4 | 8 | 8: stop, found |
| 8: stop, found | ||
| Record | Test | |
|---|---|---|
| read 1 | 8 | 8 is below 20: read on |
| 8 is below 20: read on | ||
| read 2 | 14 | 14 is below 20: read on |
| 14 is below 20: read on | ||
| read 3 | 19 | 19 is below 20: read on |
| 19 is below 20: read on | ||
| read 4 | 22 | 22 is past 20: stop, absent |
| 22 is past 20: stop, absent | ||
- A serial search stops at a matching key, or at end of file if the key is absent.
- A sequential search can stop early: once a key is past the target, the target cannot occur later. A search for 8 stops at the first record.
Serial search for 8: read 31 → 14 → 27 → 8: four records. Stop at a matching key, or at end of file if absent.
Sequential search for 20: read 8 → 14 → 19 → 22. Since 22 exceeds 20 in this ascending file, stop: 20 cannot occur later. A search for 8 stops at the first record.
Insertion must preserve the chosen order
- 1A new ID 25 goes at the end of the serial log.
- 2In the ID-ordered sequential file it belongs between 22 and 27: copy records to a new file, insert 25 at that point, then copy the remaining records.
- 3Appending alone would break key order.
1 In the serial log 31, 14, 27, 8, 22, 19, how many records are read to find 22?
2 In the sequential file, a search for 25 stops at which record? How many records are read?
3 Where does a new ID 10 go in each file?
- 15
- 2at 27, which is past 25: 5 records read
- 3serial: at the end; sequential: between 8 and 14
Random organisation and direct access
Reading every record to find one lantern is slow when a customer is waiting at the counter. Direct access uses a record’s location to reach it without first scanning all preceding records. Random organisation places records using a location derived from the record key.
Follow lantern 8: the hash points to slot 2, then the search moves on until the IDs match.
- 1Tavren uses six numbered record slots, 0–5.
- 2The hash ID MOD 6 gives the first slot to check. Records are not stored in ID or arrival order.
- 3When keys share a slot, a collision rule decides where the later record goes.
A key, a position and an index all look like numbers, but each does a different job:
| Identifier | Example | Job |
|---|---|---|
| Record key | ID 8 | Identifies the required lantern. |
| Record position | Slot 4 | Locates its stored record after collision handling. |
| Array index | Stock[4] | Selects an element in memory; it is not automatically a file address. |
A sequential file can also provide direct access
Sometimes the file must stay in ID order for the daily check, yet hires still need a quick lookup.
- 1Keep the ID-ordered file and build an index mapping each key to its record location.
- 2Search the index: key 22 maps to position 3. Retrieve position 3 and read the record directly.
- 3The file remains sequentially organised even though this access does not scan it.
1 Which slot does ID 25 hash to first with ID MOD 6?
2 Using the index above, which position holds ID 27?
3 Does random organisation mean records are placed by chance?
- 125 MOD 6 = 1
- 2position 4
- 3no: each location is worked out from the record key
Hashing algorithms
To store a record by its key, you need a rule that turns the key into a place. A hashing algorithm transforms a key into a location in a bounded address space. Use the same rule to store a record and to find it, and you always look in the right place first.
Numeric keys: use the remainder
For Tavren’s six slots, use h(ID) = ID MOD 6. MOD gives a remainder from 0 to 5, so every result is a valid slot.
The division behind each line of the figure:
| ID | Calculation | First slot |
|---|---|---|
| 31 | 31 = 5 × 6 + 1 | 1 |
| 14 | 14 = 2 × 6 + 2 | 2 |
| 27 | 27 = 4 × 6 + 3 | 3 |
| 8 | 8 = 1 × 6 + 2 | 2 |
| 22 | 22 = 3 × 6 + 4 | 4 |
| 19 | 19 = 3 × 6 + 1 | 1 |
IDs 14 and 8 both produce 2, and 31 and 19 both produce 1. Each is a collision: different keys share an initial address. It does not mean the records have the same identity.
Character keys: combine character codes, then reduce
Some keys are text, not numbers. For a text ID such as L31, add the ASCII character codes and take MOD 6. This is a different key-to-number procedure; the resulting address still needs collision handling.
- A useful hash spreads the expected keys across the available slots; a poor spread creates long searches.
- More slots or a better distribution can reduce collisions. A defined resolution method is still needed.
1 Find the first slot for ID 40 with ID MOD 6.
2 Which two of IDs 13, 20 and 26 collide?
3 Find the first slot for the text key L22 (L = 76, 2 = 50).
- 140 = 6 × 6 + 4: slot 4
- 220 and 26: both give 2 (13 gives 1)
- 376 + 50 + 50 = 176; 176 MOD 6 = 2
Hash collisions and record retrieval
Two lanterns can hash to the same slot, and only one record fits there. Linear probing checks consecutive slots after a collision, wrapping from the last slot to the first. Insertion and lookup must follow the same probe sequence, or a stored record is never found.
Tavren’s six lantern IDs collide twice under ID MOD 6. Insert 31, 14, 27, 8, 22, 19, in that arrival order. All slots are initially empty; each stored record keeps its full ID.
One row per insertion: each ID is written in the slot where it ends up.
| Slot 0 | Slot 1 | Slot 2 | Slot 3 | Slot 4 | Slot 5 | What happens | |
|---|---|---|---|---|---|---|---|
| insert 31 | 31 | 31 MOD 6 = 1: slot 1 is empty, store here | |||||
| 31 MOD 6 = 1: slot 1 is empty, store here | |||||||
| insert 14 | 14 | 14 MOD 6 = 2: slot 2 is empty, store here | |||||
| 14 MOD 6 = 2: slot 2 is empty, store here | |||||||
| insert 27 | 27 | 27 MOD 6 = 3: slot 3 is empty, store here | |||||
| 27 MOD 6 = 3: slot 3 is empty, store here | |||||||
| insert 8 | 8 | 8 MOD 6 = 2: slots 2, 3 taken; store in slot 4 | |||||
| 8 MOD 6 = 2: slots 2, 3 taken; store in slot 4 | |||||||
| insert 22 | 22 | 22 MOD 6 = 4: slot 4 taken; store in slot 5 | |||||
| 22 MOD 6 = 4: slot 4 taken; store in slot 5 | |||||||
| insert 19 | 19 | 19 MOD 6 = 1: slots 1, 2, 3, 4, 5 taken, wrap to 0; store in slot 0 | |||||
| 19 MOD 6 = 1: slots 1, 2, 3, 4, 5 taken, wrap to 0; store in slot 0 | |||||||
| end | 19 | 31 | 14 | 27 | 8 | 22 | every slot is full |
| every slot is full | |||||||
The last insertion, slot by slot: 19 finds five slots taken and wraps round to slot 0.
| ID | Hash | Slots checked | Stored at |
|---|---|---|---|
| 31 | 1 | 1 | 1 |
| 14 | 2 | 2 | 2 |
| 27 | 3 | 3 | 3 |
| 8 | 2 | 2 → 3 → 4 | 4 |
| 22 | 4 | 4 → 5 | 5 |
| 19 | 1 | 1 → 2 → 3 → 4 → 5 → 0 | 0 |
| Slot | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| ID | 19 | 31 | 14 | 27 | 8 | 22 |
Find ID 8 by comparing the stored keys
When to stop searching for a missing key
A search for a key that is not there must still end somewhere.
- 1ID 20 hashes to 2 and checks 2 → 3 → 4 → 5 → 0 → 1. After all six slots, it is absent.
- 2In a partly filled table with no deletions, reaching a never-used empty slot also proves absence.
- 3Insertion into this full table must report full rather than overwrite a different key.
- Other schemes use a separate overflow area or a linked chain for keys with the same hash.
- Store and search using that scheme’s rule: a hash alone does not identify the final location after a collision.
1 In the full table, which slots does a search for ID 27 check?
2 List the slots a search for ID 25 checks. What is the result?
3 An empty six-slot table gets IDs 12, 18 and 24, in that order. Where is each stored?
- 1slot 3 only: it matches first time
- 21 → 2 → 3 → 4 → 5 → 0: all six slots checked, so 25 is absent
- 312 in slot 0; 18 collides and goes to slot 1; 24 collides twice and goes to slot 2
Choosing organisation and access
No file suits every job: one task must preserve arrival history, another process records in key order, another retrieve and update individual records quickly. Choose from the workload, and state both the organisation and the access method.
Four Tavren jobs, each matched to a file. Read each row from the job to the reason it suits.
| Tavren requirement | Organisation and access | Reason |
|---|---|---|
| Record each lantern’s arrival at a counter | Serial file; append, then sequential access | Appending preserves the arrival sequence with no sorting step. |
| Check every lantern in ascending ID order | Sequential file; sequential access | One pass visits every record in the required order. |
| Look up one known ID during a hire | Random file; direct access using a hash | The ID leads to a location, then collision checks, avoiding a full scan in the usual case. |
| Keep an ordered list and support individual lookups | Sequential file with an index; direct access | The index supplies the record address while the file retains key order. |
Update one record in each kind of file
Files are changed as well as read. When lantern 8 is hired, its status goes from available to on-loan and its ID stays 8. Each kind of file makes that change differently.
- 1Random file: find slot 4 through the hash and probing rule, read the record, change Status and write it back to slot 4. Other records stay in place.
- 2Simple sequential file: read each old record and write a new file, replacing the matching record’s status and copying every other record unchanged. This preserves ID order.
- 3Indexed fixed-record file: a direct update at the indexed location.
What each method costs
Speed at the counter is not free.
- Random access needs an address rule, collision handling and spare capacity.
- An index needs storage, and maintenance when record locations change.
- Sequential scanning suits a task that already needs every record; a direct lookup suits a task that needs one known key.
1 Every night, a library prints all members’ records in membership-number order. Which organisation and access fit?
2 A help desk looks up one customer by ID while they wait. Which organisation and access fit?
3 Why does a simple sequential file write a new file to change one record?
- 1sequential file, sequential access: every record is needed, in key order
- 2random file with direct access by hashing the ID: one known key, found quickly
- 3the records are copied in order into the new file, so the key order is kept while one record changes