turing_machine_rs/instruction/
mod.rs

1//! Provides [`Instruction`] and it's components: [`Head`], [`Move`],
2//! [`State`], [`Tail`].
3//!
4//! This module provides a unit struct named [`Instruction`] for implementing
5//! this type for any type that implements [`Symbol`] trait.
6//!
7//! # Examples
8//! Creating a new [`Instruction`] through the [`Instruction::new`] method:
9//! ```rust
10//! use turing_machine_rs::instruction::{Head, Instruction, Move, State, Tail};
11//!
12//! let head = Head::new(State(1), '0');
13//! let tail = Tail::new(State(0), '0', Move::Right);
14//!
15//! // Moves head and tail from the scope
16//! let inst = Instruction::new(head, tail);
17//! ```
18//!
19//! Creating a new [`Instruction`] through the [`Instruction::build`] method:
20//! ```rust
21//! use turing_machine_rs::instruction::{Instruction, Move, State};
22//!
23//! let inst = Instruction::build(State(1), '0', State(0), '0', Move::Right);
24//! ```
25
26mod head;
27mod movement;
28mod state;
29mod tail;
30
31pub use head::Head;
32pub use movement::Move;
33pub use state::State;
34pub use tail::Tail;
35
36use std::fmt::{Display, Error, Formatter};
37
38use crate::Symbol;
39
40/// [`Instruction`] is a component of [`crate::program::Program`]. This struct
41/// contains a [`Head`] struct and a [`Tail`] struct and is used as a unit for
42/// instructions in the program.
43///
44/// [`Instruction`] fileds doesn't needs in control or protection so they
45/// are public.
46#[derive(Clone, Debug, Eq, PartialEq)]
47pub struct Instruction<S: Symbol> {
48    /// The first part of an instruction contains the state [`State`]
49    /// and a symbol of the type that implements the [`Symbol`] trait.
50    pub head: Head<S>,
51    /// The second part of an instruction contains the state [`State`],
52    /// a symbol of the type that implements the [`Symbol`] trait
53    /// and the movement [`Move`].
54    pub tail: Tail<S>,
55}
56
57impl<S: Symbol> Instruction<S> {
58    /// Constructs a new [`Instruction`] with the [`Head`] and the [`Tail`].
59    pub fn new(head: Head<S>, tail: Tail<S>) -> Self {
60        Instruction { head, tail }
61    }
62
63    /// Builds an [`Instruction`] from the [`Head`] and the [`Tail`] parts.
64    pub fn build(
65        h_state: State,
66        h_symbol: S,
67        t_state: State,
68        t_symbol: S,
69        t_movement: Move,
70    ) -> Self {
71        Instruction::new(
72            Head::new(h_state, h_symbol),
73            Tail::new(t_state, t_symbol, t_movement),
74        )
75    }
76}
77
78impl<S: Symbol> Display for Instruction<S> {
79    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
80        write!(f, "({}) -> ({})", self.head, self.tail)
81    }
82}