allocate-registers jump, compare allocate-registers zero, one, two, nil allocate-registers free allocate-registers lst, end, cell, element ;; Initialize constant registers li zero, 0 ; zero is useful for copying one register's contents to another li one, 1 ; one is useful for allocating a memory location li two, 2 ; two is useful for allocating two consecutive memory locations li nil, -1 ; nil represents an empty list ;; Initialize the free register to point to the beginning of memory li free, 0 ; free points to the next available memory location ;; Read a list into memory: lst points to the start; end points to the end ; Allocate a memory location for a pointer to the start of the list add lst, free, zero add free, free, one ; The just-allocate memory location is the initial end of the list add end, lst, zero read-element: ; Read a number to find out if there is another element in the list ; (0 means there is no more element in the list) read element li jump, read-end jeqz element, jump ; Read the next element in the list read element ; Allocate two consecutive memory locations for the new element and for ; a pointer to the rest of the list add cell, free, zero add free, free, two st element, cell st cell, end add end, cell, one ; Loop li jump, read-element j jump read-end: ; Terminate the list: the rest of the list is the empty list st nil, end ld lst, lst ;; Print the list starting at lst print: ; Stop if the list is empty seq compare, lst, nil li jump, print-1 jeqz compare, jump halt print-1: ; Print the current element ld element, lst write element ; Advance lst to the rest of the list add lst, lst, one ld lst, lst ; Continue with the rest of the list li jump, print j jump test empty-list >>> 0 test singleton-list >>> 1 >>> 3 >>> 0 3 test non-empty-list >>> 1 >>> 3 >>> 100 >>> 10 >>> -1 >>> -2 >>> 0 3 10 -2