Created
July 28, 2017 23:06
-
-
Save cameronp98/a0acd1920c54afcb63f1d59adc227fc1 to your computer and use it in GitHub Desktop.
Banana state machine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #[derive(Debug)] | |
| struct StateMachine<S> { | |
| string: String, | |
| state: S, | |
| } | |
| #[derive(Debug)] | |
| struct Start; | |
| impl StateMachine<Start> { | |
| fn new() -> Self { | |
| StateMachine { | |
| string: String::new(), | |
| state: Start, | |
| } | |
| } | |
| fn b(self) -> StateMachine<B> { | |
| StateMachine::<B>::new() | |
| } | |
| } | |
| #[derive(Debug)] | |
| struct B; | |
| impl StateMachine<B> { | |
| fn new() -> Self { | |
| println!("B"); | |
| StateMachine { | |
| string: String::from("B"), | |
| state: B, | |
| } | |
| } | |
| fn a(self) -> StateMachine<A> { | |
| StateMachine::<A>::new(self.string) | |
| } | |
| } | |
| #[derive(Debug)] | |
| struct A; | |
| impl StateMachine<A> { | |
| fn new(string: String) -> Self { | |
| println!("a"); | |
| StateMachine { | |
| string: string + "a", | |
| state: A, | |
| } | |
| } | |
| fn n(self) -> StateMachine<N> { | |
| StateMachine::<N>::new(self.string) | |
| } | |
| } | |
| #[derive(Debug)] | |
| struct N; | |
| impl StateMachine<N> { | |
| fn new(string: String) -> Self { | |
| println!("n"); | |
| StateMachine { | |
| string: string + "n", | |
| state: N, | |
| } | |
| } | |
| fn a(self) -> StateMachine<A> { | |
| StateMachine::<A>::new(self.string) | |
| } | |
| } | |
| #[derive(Debug)] | |
| enum StateMachineWrapper { | |
| Start(StateMachine<Start>), | |
| B(StateMachine<B>), | |
| A(StateMachine<A>), | |
| N(StateMachine<N>), | |
| } | |
| impl StateMachineWrapper { | |
| fn step(self, input: char) -> StateMachineWrapper { | |
| match (self, input) { | |
| (StateMachineWrapper::Start(empty), 'B') => StateMachineWrapper::B(empty.b()), | |
| (StateMachineWrapper::B(b), 'a') => StateMachineWrapper::A(b.a()), | |
| (StateMachineWrapper::A(a), 'n') => StateMachineWrapper::N(a.n()), | |
| (StateMachineWrapper::N(n), 'a') => StateMachineWrapper::A(n.a()), | |
| _ => panic!("Invalid input {}", input), | |
| } | |
| } | |
| } | |
| fn main() { | |
| let mut wrapper = StateMachineWrapper::Start(StateMachine::<Start>::new()); | |
| for c in "Banana".chars() { | |
| wrapper = wrapper.step(c); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment