How can I assign a natural number to a register (a register is represented by natural number).
For example how do I load a natural number n to register k? How can I compare two natural numbers and assign to a register?
My thinking is to define an inductive type with n, k as natural numbers but I'm not sure what the constructors should be like....
I'm doing something like:
Inductive assign (n, k : nat) Type :=
| load k => k
| load k n =>
One way to do this is to represent the state of all registers as a function from the register number to the stored natural number. We can define a register type indexed by natural numbers as follows:
This is not strictly necessary, but having a separate type for registers prevents confusion between the registers and the natural numbers they store. A state then is just a function from register to nat, and in the empty state we can consider every register to hold the value zero.
The assignment operation can now be implemented as a function that takes a state and returns a new state with the specified register taking on a new value. To define this we need to prove a quick theorem establishing that register equality is decidable:
Here's an example showing that this works. We can assign the value 5 into register 0 and successfully read it back out again:
This code is inspired by the update function defined in the Imp chapter of Software Foundations by Pierce et al. There they solve a similar problem but use "variables" instead of "registers."