NB. a small memory containing a machine language
NB. program for c =: a + b

NB. Computer tracing control
trace =: 0

NB. Memory model
mem =: 0 0 0 0 307 108 409 22 3 0

NB. memory operations

access =. monad define script
y. from mem
)

store =. monad define script
mem =: (1 from y.) (0 from y.) amend mem
)

NB. the processor registers

pc =: 0
ir =: 0
ac =: 0

NB. the processor model

proc =. monad define script
whilst. y. do.
	NB. show registers and memory if tracing
	displayRegisters ''
	NB. fetch instruction
	ir =: access pc
	NB. increment pc
	pc =: pc + 1
	NB. decode instruction
	('opCode' ; 'address') =. 100 100 rep ir
	NB. interpret instruction
	if. opCode = 1
		do. ac =: ac + access address continue. end.
	if. opCode = 2
		do. ac =: ac - access address continue. end.
	if. opCode = 3
		do. ac =: access address continue. end.
	if. opCode = 4
		do. store address , ac continue.
		else. 'invalid operation code' break. end.
end.
)

NB. the tracing function

displayRegisters =. monad define script
if. trace
	do.
		display 'pc= ' , (format pc) , ', ir= ' , (format ir) , ', ac= ' , format ac
		display 'mem= ' , format mem
	else.	0
	end.
)
