3 ms·
Like JavaScript Allongé, I am planning for it to be readable by someone with just a smattering of programming familiarity. But also like JavaScript Allongé, I h
by braythwayt 10y ago
Like JavaScript Allongé, I am planning for it to be readable by someone with just a smattering of programming familiarity. But also like JavaScript Allongé, I hope for a fairly substantial learning slope.
I don’t imagine writing the first interpreter will be onerous. Here’s one I wrote specifically to be “pessimum” without being gratuitously so:
const aMachine = (() => {
const HALT = 'HALT';
const LEFT = 2;
const RIGHT = 3;
function kiss4({ description, tape: _tape }) {
const tape = Array.from(_tape);
let tapeIndex = 0;
let currentState = description[0][0];
while (true) {
if (tapeIndex < 0) {
console.log('moved off the left edge of the world');
console.log({ tapeIndex, currentState, currentMark, tape: tape.join(' ') });
return tape;
}
const currentMark = tape[tapeIndex];
const rule = description.find(([state, mark]) => state === currentState && mark === currentMark);
if (rule == null) {
if (currentState !== HALT) {
console.log('no rule for this state and mark');
console.log({ tapeIndex, currentState, currentMark, tape: tape.join(' ') });
}
return tape;
}
const [_, __, nextState, action] = rule;
if (action === LEFT) {
--tapeIndex;
} else if (action === RIGHT) {
++tapeIndex;
if (tape[tapeIndex] == null) tape[tapeIndex] = 0;
} else if ([0, 1].includes(action)) {
tape[tapeIndex] = action;
}
currentState = nextState;
}
}
return Object.assign(
({ description, tape = [] }) => kiss4({ description, tape }),
{ constants: { LEFT, RIGHT, HALT } }
);
})();