allocate-registers jump, compare allocate-registers zero, one, two, nil allocate-registers free allocate-registers lst, end, cell, element, target ;; 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 ;; Check whether the list starting at lst contains a given element ; Find out from the user what we are looking for read target member: ; Print 0 and stop if the list is empty seq compare, lst, nil li jump, member-1 jeqz compare, jump write zero halt member-1: ; Print 1 and stop if the first element in the list is the target ld element, lst seq compare, element, target li jump, member-2 jeqz compare, jump write one halt member-2: ; Advance lst to the rest of the list add lst, lst, one ld lst, lst ; Continue with the rest of the list li jump, member j jump test empty-list >>> 0 >>> 10 ; target 0 test singleton-list-not-found >>> 1 >>> 3 >>> 0 >>> 10 ; target 0 test singleton-list-found >>> 1 >>> 3 >>> 0 >>> 3 ; target 1 test non-empty-list-not-found >>> 1 >>> 3 >>> 100 >>> 10 >>> -1 >>> -2 >>> 0 >>> -10 ; target 0 test non-empty-list-found >>> 1 >>> 3 >>> 100 >>> 10 >>> -1 >>> -2 >>> 0 >>> 10 ; target 1