CARDIAC › Tips and tricks › Comparisons
Put the threshold at 0 and make the thing you test reach it
Say you want to do something five times.
You'd probably count from 0 up to 5 and check at the top of each pass whether you're still under 5. That's how it looks in most languages, and it works here, but it costs more than it looks. The check is a SUB and a cell to hold the 5, and because TAC only jumps when the answer is negative, you need a JMP to get out of the loop and another at the bottom to get back in.
cell contents notes
10 130 CLA 30 cells 10-13: still below 5? TAC into the body, else JMP out
11 731 SUB 31
12 314 TAC 14
13 819 JMP 19
14 532 OUT 32 cells 14-19: the body, then count one more and go back to the test
15 130 CLA 30
16 200 ADD 00
17 630 STO 30
18 810 JMP 10
19 900 HRS 00
30 000 the count
31 005 the limit
32 042 what the body prints
Step through the natural way in Cardigan
Here's the trick: count from -5 up to 0 instead, and test at the bottom. TAC only ever asks "is this below zero?", and while your count is still negative the answer is yes, so TAC's jump is what takes you round again. There's no limit to subtract, and both JMPs disappear.
cell contents notes
10 532 OUT 32 cells 10-15: the body, then count up; TAC goes round while the count is negative
11 130 CLA 30
12 200 ADD 00
13 630 STO 30
14 310 TAC 10
15 900 HRS 00
30 -005 the count, from -5
32 042 what the body prints
Step through the CARDIAC way in Cardigan
Both print 42 five times. The first takes 13 cells and runs 45 instructions; the second takes 8 cells and runs 26. Same loop, a lot less work, and you'll find this shape all over good CARDIAC code.
From the tips in
cardiac-code on GitHub. All the tips.