Compare commits

..
1 Commits
Author SHA1 Message Date
leonhard 8e90c8b2db feat: add tape head movement and dynamic growth 2026-11-11 16:19:05 +01:00
3 changed files with 30 additions and 325 deletions

No files matched your search

-47
View File
@@ -1,49 +1,2 @@
mod machine;
mod tape;
use std::fmt::Display;
pub use machine::NextState;
pub use machine::StateId;
pub use machine::TuringMachine;
#[derive(Debug)]
pub enum TuringMachineError {
DuplicateStateEntryKey(String),
StateEntryParsing(String),
}
impl Display for TuringMachineError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use TuringMachineError::*;
match self {
DuplicateStateEntryKey(key) => write!(f, "duplicate key in state table: {}", key),
StateEntryParsing(entry) => write!(f, "could not parse state entry: {}", entry),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn busy_beaver_2() {
let mut machine = TuringMachine::with_state_entries(
[
"A|0|1;R;B",
"A|1|1;L;C",
"B|0|1;L;A",
"B|1|1;R;B",
"C|0|1;L;B",
"C|1|1;R;-HALT-",
]
.into_iter(),
"A",
)
.unwrap();
while let NextState::State(_) = machine.step() {}
assert_eq!(machine.peek(4).to_string(), " 1 1 1 1 [1] 1 0 0 ");
}
}
+24 -167
View File
@@ -1,185 +1,42 @@
use std::{collections::HashMap, fmt::Display, num::NonZeroUsize};
use std::{collections::HashMap, num::NonZeroUsize};
use crate::{
TuringMachineError,
tape::{Tape, TapePeek, TapeSymbol},
};
use crate::tape::{Tape, TapeSymbol};
pub struct TuringMachine {
state_table: HashMap<(StateId, TapeSymbol), Action>,
current_state: NextState,
#[derive(Default)]
struct TuringMachine {
state_table: HashMap<(MachineState, TapeSymbol), MachineAction>,
tape: Tape,
}
impl<'a> TuringMachine {
pub fn with_state_entries(
state_entries: impl Iterator<Item = &'a str>,
initial_state: &str,
) -> Result<Self, TuringMachineError> {
let current_state = NextState::State(StateId::try_from(initial_state)?);
let mut state_table = HashMap::new();
for state_entry in state_entries {
let StateEntry((state, symbol, action)) = state_entry.try_into()?;
if state_table.contains_key(&(state, symbol)) {
return Err(TuringMachineError::DuplicateStateEntryKey(format!(
"there already exists a state entry with state {}, symbol {}",
state, symbol
)));
}
state_table.insert((state, symbol), action);
}
Ok(TuringMachine {
state_table,
current_state,
tape: Tape::default(),
})
}
}
impl TuringMachine {
pub fn step(&mut self) -> NextState {
let state_number = match self.current_state {
NextState::Halt => return NextState::Halt,
NextState::State(id) => id,
};
let symbol = self.tape.get_symbol();
match self.state_table.get(&(state_number, symbol)) {
None => {
self.current_state = NextState::Halt;
NextState::Halt
}
Some(Action {
tape_write,
movement,
new_state,
}) => {
self.tape.write_symbol(*tape_write);
self.tape.move_head(movement);
self.current_state = *new_state;
*new_state
}
fn new() -> Self {
TuringMachine::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);
}
machine
}
}
impl<'a> TuringMachine {
pub fn peek(&'a self, radius: usize) -> TapePeek<'a> {
self.tape.peek(radius)
}
#[derive(Eq, Hash, PartialEq)]
enum MachineState {
Halt,
StateNumber(NonZeroUsize),
}
const ALPHABET: [char; 26] = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
];
struct StateEntry((StateId, TapeSymbol, Action));
impl TryFrom<&str> for StateEntry {
type Error = TuringMachineError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let mut fields = value.split('|');
let state_id = StateId::try_from(fields.next().ok_or(
TuringMachineError::StateEntryParsing("empty entry".to_owned()),
)?)?;
let tape_symbol = TapeSymbol::try_from(fields.next().ok_or(
TuringMachineError::StateEntryParsing("missing field for tape symbol".to_owned()),
)?)?;
let action = Action::try_from(fields.next().ok_or(TuringMachineError::StateEntryParsing(
"missing field for action".to_owned(),
))?)?;
Ok(StateEntry((state_id, tape_symbol, action)))
}
}
#[derive(Eq, Hash, PartialEq, Clone, Copy)]
pub struct StateId(NonZeroUsize);
impl Display for StateId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl TryFrom<&str> for StateId {
type Error = TuringMachineError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let mut id: usize = 0;
for c in value.chars() {
let digit = ALPHABET.iter().position(|letter| *letter == c).ok_or(
TuringMachineError::StateEntryParsing(format!("state id: {}", value)),
)? + 1;
id = id * 26 + digit;
}
Ok(StateId(NonZeroUsize::new(id).ok_or(
TuringMachineError::StateEntryParsing(format!("state id: {}", value)),
)?))
}
}
struct Action {
struct MachineAction {
tape_write: TapeSymbol,
movement: Movement,
new_state: NextState,
movement: MachineMovement,
new_state: MachineState,
}
impl TryFrom<&str> for Action {
type Error = TuringMachineError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let mut fields = value.split(';');
let tape_write = TapeSymbol::try_from(fields.next().ok_or(
TuringMachineError::StateEntryParsing("empty action".to_owned()),
)?)?;
let movement = Movement::try_from(fields.next().ok_or(
TuringMachineError::StateEntryParsing("missing field for movement".to_owned()),
)?)?;
let new_state = NextState::try_from(fields.next().ok_or(
TuringMachineError::StateEntryParsing("missing field for next state".to_owned()),
)?)?;
Ok(Action {
tape_write,
movement,
new_state,
})
}
}
pub enum Movement {
pub enum MachineMovement {
Left,
Right,
}
impl TryFrom<&str> for Movement {
type Error = TuringMachineError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"L" => Ok(Movement::Left),
"R" => Ok(Movement::Right),
s => Err(TuringMachineError::StateEntryParsing(format!(
"machine movement: {}",
s
))),
}
}
}
#[derive(Eq, Hash, PartialEq, Clone, Copy)]
pub enum NextState {
Halt,
State(StateId),
}
impl TryFrom<&str> for NextState {
type Error = TuringMachineError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"-HALT-" => Ok(NextState::Halt),
v => Ok(NextState::State(StateId::try_from(v)?)),
}
}
}
+6 -111
View File
@@ -1,27 +1,16 @@
use std::fmt::Display;
use crate::{TuringMachineError, machine::Movement};
use crate::machine::MachineMovement;
#[derive(Default)]
pub struct Tape {
left_half: Vec<TapeSymbol>,
right_half: Vec<TapeSymbol>,
head: HeadPosition,
}
impl Default for Tape {
fn default() -> Self {
Self {
left_half: vec![TapeSymbol::Zero],
right_half: vec![TapeSymbol::Zero],
head: Default::default(),
}
}
}
impl Tape {
pub fn move_head(&mut self, direction: &Movement) {
pub fn move_head(&mut self, direction: &MachineMovement) {
match &direction {
Movement::Left => {
MachineMovement::Left => {
if self.head.is_right_side() {
if self.head.index == 0 {
self.head.side = TapeSide::Left;
@@ -35,7 +24,7 @@ impl Tape {
}
}
}
Movement::Right => {
MachineMovement::Right => {
if self.head.is_left_side() {
if self.head.index == 0 {
self.head.side = TapeSide::Right;
@@ -51,114 +40,20 @@ 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,
TapeSide::Right => self.right_half[self.head.index] = symbol,
}
}
pub fn peek(&self, radius: usize) -> TapePeek<'_> {
let mut fields = Vec::new();
match self.head.side {
TapeSide::Left => {
let left_lower_bound = self.head.index.saturating_sub(radius);
let left_upper_bound = self.head.index + radius;
let left_overshoot = left_upper_bound.saturating_sub(self.left_half.len());
let right_upper_bound = radius.saturating_sub(self.head.index);
let right_overshoot = right_upper_bound.saturating_sub(self.right_half.len());
fields.resize(left_overshoot, &TapeSymbol::Zero);
let left_side = self.left_half[left_lower_bound..left_upper_bound - left_overshoot]
.iter()
.rev();
fields.extend(left_side);
let right_side = self.right_half[..right_upper_bound].iter();
fields.extend(right_side);
fields.resize(fields.len() + right_overshoot, &TapeSymbol::Zero);
}
TapeSide::Right => {
let right_lower_bound = self.head.index.saturating_sub(radius);
let right_upper_bound = self.head.index + radius;
let right_overshoot = right_upper_bound.saturating_sub(self.right_half.len());
let left_upper_bound = radius.saturating_sub(self.head.index);
let left_overshoot = left_upper_bound.saturating_sub(self.left_half.len());
fields.resize(left_overshoot, &TapeSymbol::Zero);
let left_side = self.left_half[..left_upper_bound].iter().rev();
fields.extend(left_side);
let right_side =
self.right_half[right_lower_bound..right_upper_bound - right_overshoot].iter();
fields.extend(right_side);
fields.resize(fields.len() + right_overshoot, &TapeSymbol::Zero);
}
}
TapePeek(fields)
}
}
pub struct TapePeek<'a>(Vec<&'a TapeSymbol>);
impl Display for TapePeek<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let middle = self.0.len() / 2;
for (index, symbol) in self.0.iter().enumerate() {
if index == middle {
write!(f, "[{}]", symbol)?;
} else {
write!(f, " {} ", symbol)?;
}
}
Ok(())
}
}
#[derive(Eq, Hash, PartialEq, Clone, Copy)]
#[derive(Eq, Hash, PartialEq)]
pub enum TapeSymbol {
Zero,
One,
}
impl Display for TapeSymbol {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TapeSymbol::Zero => write!(f, "0"),
TapeSymbol::One => write!(f, "1"),
}
}
}
impl Default for TapeSymbol {
fn default() -> Self {
TapeSymbol::Zero
}
}
impl TryFrom<&str> for TapeSymbol {
type Error = TuringMachineError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"0" => Ok(TapeSymbol::Zero),
"1" => Ok(TapeSymbol::One),
s => Err(TuringMachineError::StateEntryParsing(format!(
"tape symbol: {}",
s
))),
}
}
}
#[derive(Default)]
struct HeadPosition {
side: TapeSide,