Compare commits

..
9 Commits
3 changed files with 385 additions and 28 deletions

No files matched your search

+47
View File
@@ -1,2 +1,49 @@
mod machine; mod machine;
mod tape; 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 ");
}
}
+166 -25
View File
@@ -1,44 +1,185 @@
use std::{collections::HashMap, num::NonZeroU8}; use std::{collections::HashMap, fmt::Display, num::NonZeroUsize};
use crate::tape::{Tape, TapeSymbol}; use crate::{
TuringMachineError,
tape::{Tape, TapePeek, TapeSymbol},
};
const MAX_STATE_COUNT: u8 = 255; pub struct TuringMachine {
state_table: HashMap<(StateId, TapeSymbol), Action>,
#[derive(Default)] current_state: NextState,
struct TuringMachine {
state_table: HashMap<(MachineState, TapeSymbol), MachineAction>,
tape: Tape, 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 { impl TuringMachine {
fn new() -> Self { pub fn step(&mut self) -> NextState {
Default::default() 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 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
} }
} }
#[derive(Eq, Hash, PartialEq)] impl<'a> TuringMachine {
enum MachineState { pub fn peek(&'a self, radius: usize) -> TapePeek<'a> {
Halt, self.tape.peek(radius)
StateNumber(NonZeroU8), }
} }
struct MachineAction { 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 {
tape_write: TapeSymbol, tape_write: TapeSymbol,
movement: MachineMovement, movement: Movement,
new_state: MachineState, new_state: NextState,
} }
enum MachineMovement { 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 {
Left, Left,
Right, 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)?)),
}
}
}
+172 -3
View File
@@ -1,18 +1,187 @@
#[derive(Default)] use std::fmt::Display;
use crate::{TuringMachineError, machine::Movement};
pub struct Tape { pub struct Tape {
left_half: Vec<TapeSymbol>, left_half: Vec<TapeSymbol>,
right_half: Vec<TapeSymbol>, right_half: Vec<TapeSymbol>,
head: isize, head: HeadPosition,
} }
#[derive(Eq, Hash, PartialEq)] 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) {
match &direction {
Movement::Left => {
if self.head.is_right_side() {
if self.head.index == 0 {
self.head.side = TapeSide::Left;
} else {
self.head.index -= 1;
}
} else {
self.head.index += 1;
if self.head.index == self.left_half.len() {
self.left_half.push(TapeSymbol::default());
}
}
}
Movement::Right => {
if self.head.is_left_side() {
if self.head.index == 0 {
self.head.side = TapeSide::Right;
} else {
self.head.index -= 1;
}
} else {
self.head.index += 1;
if self.head.index == self.right_half.len() {
self.right_half.push(TapeSymbol::default());
}
}
}
}
}
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)]
pub enum TapeSymbol { pub enum TapeSymbol {
Zero, Zero,
One, 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 { impl Default for TapeSymbol {
fn default() -> Self { fn default() -> Self {
TapeSymbol::Zero 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,
index: usize,
}
impl HeadPosition {
fn is_left_side(&self) -> bool {
matches!(self.side, TapeSide::Left)
}
fn is_right_side(&self) -> bool {
!self.is_left_side()
}
}
enum TapeSide {
Left,
Right,
}
impl Default for TapeSide {
fn default() -> Self {
TapeSide::Right
}
}