feat: implement a single turing machine step

This commit is contained in:
leonhard committed 2026-11-15 16:49:32 +01:00
1 parent d2ad40262b
commit 31a5c96fbf
2 files changed
+46 -14

No files matched your search

+38 -13
View File
@@ -2,32 +2,57 @@ use std::{collections::HashMap, num::NonZeroUsize};
use crate::tape::{Tape, TapeSymbol};
#[derive(Default)]
struct TuringMachine {
state_table: HashMap<(MachineState, TapeSymbol), MachineAction>,
state_table: HashMap<(StateNumberType, TapeSymbol), MachineAction>,
current_state: MachineState,
tape: Tape,
}
impl TuringMachine {
fn new() -> Self {
TuringMachine::default()
fn with_state_entries(
state_entries: impl Iterator<Item = (StateNumberType, TapeSymbol, MachineAction)>,
initial_state: MachineState,
) -> Self {
let mut state_table = HashMap::new();
for (state, symbol, action) in state_entries {
state_table.insert((state, symbol), action);
}
TuringMachine {
state_table,
current_state: initial_state,
tape: Tape::default(),
}
}
fn with_state_entries(
state_entries: impl Iterator<Item = (MachineState, TapeSymbol, MachineAction)>,
) -> Self {
let mut machine = TuringMachine::new();
for (state, symbol, action) in state_entries {
machine.state_table.insert((state, symbol), action);
fn step(&mut self) {
let state_number = match self.current_state {
MachineState::Halt => return,
MachineState::StateNumber(n) => n,
};
let symbol = self.tape.get_symbol();
match self.state_table.get(&(state_number, symbol)) {
None => {
self.current_state = MachineState::Halt;
}
Some(MachineAction {
tape_write,
movement,
new_state,
}) => {
self.tape.write_symbol(*tape_write);
self.tape.move_head(movement);
self.current_state = *new_state;
}
}
machine
}
}
#[derive(Eq, Hash, PartialEq)]
type StateNumberType = NonZeroUsize;
#[derive(Eq, Hash, PartialEq, Clone, Copy)]
enum MachineState {
Halt,
StateNumber(NonZeroUsize),
StateNumber(StateNumberType),
}
struct MachineAction {
+8 -1
View File
@@ -50,6 +50,13 @@ impl Tape {
}
}
pub fn get_symbol(&self) -> TapeSymbol {
match self.head.side {
TapeSide::Left => self.left_half[self.head.index],
TapeSide::Right => self.right_half[self.head.index],
}
}
pub fn write_symbol(&mut self, symbol: TapeSymbol) {
match self.head.side {
TapeSide::Left => self.left_half[self.head.index] = symbol,
@@ -58,7 +65,7 @@ impl Tape {
}
}
#[derive(Eq, Hash, PartialEq)]
#[derive(Eq, Hash, PartialEq, Clone, Copy)]
pub enum TapeSymbol {
Zero,
One,