Generating Repetitive Code for Nand2Tetris in Python

programming
python
nand2tetris
tutorial
trivial
computer-science
electronics
Author

Ritobrata Ghosh

Published

June 9, 2023

Introduction

The Hardware Definition Language (HDL) defined in the nand2tetris software suite is barebones, as HDLs should be. But it often leads to us writing repetitive code. This might become annoying.

Like, really annoying.

My Solution

In the first chapter itself, there are chips that you have to design for which you have to write a lot of repetitive code.

I am talking about the Or16, And16, and Not16 chips.

I will give one example. The Or16.hdl file that implements the 16-way Or gate looks like this:

// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/01/Or16.hdl

/**
 * 16-bit bitwise Or:
 * for i = 0..15 out[i] = (a[i] or b[i])
 */

CHIP Or16 {
    IN a[16], b[16];
    OUT out[16];

    PARTS:
    Or (a=a[0], b=b[0], out=out[0]);
    Or (a=a[1], b=b[1], out=out[1]);
    Or (a=a[2], b=b[2], out=out[2]);
    Or (a=a[3], b=b[3], out=out[3]);
    Or (a=a[4], b=b[4], out=out[4]);
    Or (a=a[5], b=b[5], out=out[5]);
    Or (a=a[6], b=b[6], out=out[6]);
    Or (a=a[7], b=b[7], out=out[7]);
    Or (a=a[8], b=b[8], out=out[8]);
    Or (a=a[9], b=b[9], out=out[9]);
    Or (a=a[10], b=b[10], out=out[10]);
    Or (a=a[11], b=b[11], out=out[11]);
    Or (a=a[12], b=b[12], out=out[12]);
    Or (a=a[13], b=b[13], out=out[13]);
    Or (a=a[14], b=b[14], out=out[14]);
    Or (a=a[15], b=b[15], out=out[15]);
}

There is a lot of repetition!

However, once we understand the format, we can simply write two lines of Python, or a language of your choice to generate the repetitive code.

The Code

The code is trivial, and looks like this:

for i in range(0, 16):
    print(f'    Or (a=a[{i}], b=b[{i}], out=out[{i}]);')

This gives you the output that you need.

Code in Action

All you need to do now is just copy the code and paste it into your chip HDL file.

You can repeat the same process for the And, and Not gates as well.

Conclusion

This was such a trivial program and easy to write, and it saved me probably some minutes. But as I was doing this, I realized, Computer Science is a field of study that rewards your laziness- if you are being lazy in the correct way. The old ways of: “do not take shortcuts” do not apply here. Take shortcuts that save you time, money, or teach you new things.