CARDIAC › Tips and tricks › Subroutines
Call a routine through its address
Say you want to apply a function to each card in a stack, and the first card says which function: double, or times ten.
The usual way is to pass a number saying which function you want, and test it before every call. That's a test for every card, and another for every function you add.
cell contents notes
10 030 INP 30 cell 10: which function: 0 for double, -1 for times ten
11 031 INP 31 cells 11-13: each card until a negative one
12 131 CLA 31
13 322 TAC 22
14 130 CLA 30 cells 14-18: test the choice, then call one function or the other
15 318 TAC 18
16 840 JMP 40
17 819 JMP 19
18 845 JMP 45
19 632 STO 32 cells 19-22: print what came back
20 532 OUT 32
21 811 JMP 11
22 900 HRS 00
30 000 the choice
31 000 the card
32 000
40 199 CLA 99 cells 40-44: double the card
41 644 STO 44
42 131 CLA 31
43 231 ADD 31
44 000 the return address
45 199 CLA 99 cells 45-49: ten times the card
46 649 STO 49
47 131 CLA 31
48 410 SFT 10
49 000 the return address
Step through the natural way in Cardigan
On CARDIAC a routine is just the address of its first cell, so pass the address itself. JMP 00 is 800, and adding the address to it makes the call, JMP 40 or JMP 45. Store it once, before the loop, and every card after that goes straight to the right function. The loop doesn't know or care how many functions there are, and a function written later works without changing it.
cell contents notes
10 030 INP 30 cells 10-13: the function is its address; JMP 00 plus the address is the call
11 130 CLA 30
12 233 ADD 33
13 617 STO 17
14 031 INP 31 cells 14-21: each card until a negative one: call the function, print what came back
15 131 CLA 31
16 321 TAC 21
17 800 JMP 00 JMP f, written by cell 13
18 632 STO 32
19 532 OUT 32
20 814 JMP 14
21 900 HRS 00
30 000 the function's address
31 000 the card
32 000
33 800 JMP 00
40 199 CLA 99 cells 40-44: double the card
41 644 STO 44
42 131 CLA 31
43 231 ADD 31
44 000 the return address
45 199 CLA 99 cells 45-49: ten times the card
46 649 STO 49
47 131 CLA 31
48 410 SFT 10
49 000 the return address
Step through the CARDIAC way in Cardigan
Doubling 3 and 5 prints 6 and 10 both ways. Testing takes 26 cells and runs 35 instructions; calling through the address takes 26 cells and runs 32. Each card costs 12 instructions instead of 14 or 15, and making the call costs 3, once. The functions return through cell 99 as Brian L. Stuart's CARDIAC page shows, and the call is built the way that page builds its indirect loads and stores, by adding an address to an instruction and running it.
On any other machine you'd call this a function pointer. C's qsort takes its comparison this way, and a C++ virtual call does the same with one more step, fetching the address from the object's table of functions, its vtable, and calling through it.
From the tips in
cardiac-code on GitHub. All the tips.