Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 11 additions & 13 deletions exercises/forth/example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ use std::collections::HashMap;
use std::collections::LinkedList;
use std::str::FromStr;

use Term::*;

pub type Value = i32;
pub type ForthResult = Result<(), Error>;
type StackResult<T> = Result<T, Error>;
Expand Down Expand Up @@ -39,11 +37,11 @@ impl FromStr for Term {

fn from_str(s: &str) -> Result<Term, ()> {
match s {
":" => Ok(StartDefinition),
";" => Ok(EndDefinition),
":" => Ok(Term::StartDefinition),
";" => Ok(Term::EndDefinition),
_ => Err(()),
}.or_else(|_| Value::from_str(s).map(Number))
.or_else(|_| Ok(Word(s.to_ascii_lowercase())))
}.or_else(|_| Value::from_str(s).map(Term::Number))
.or_else(|_| Ok(Term::Word(s.to_ascii_lowercase())))
}
}

Expand All @@ -68,18 +66,18 @@ impl Forth {

fn run(&mut self) -> ForthResult {
while let Some(term) = self.code.pop_front() {
try!(self.step_term(term))
self.step_term(term)?
}

Forth::ok()
}

fn step_term(&mut self, term: Term) -> ForthResult {
match term {
Number(value) => self.push(value),
Word(word) => self.step_word(&word),
StartDefinition => self.store_definition(),
EndDefinition => Err(Error::InvalidWord),
Term::Number(value) => self.push(value),
Term::Word(word) => self.step_word(&word),
Term::StartDefinition => self.store_definition(),
Term::EndDefinition => Err(Error::InvalidWord),
}
}

Expand Down Expand Up @@ -113,13 +111,13 @@ impl Forth {

loop {
match self.code.pop_front() {
Some(EndDefinition) => break,
Some(Term::EndDefinition) => break,
Some(term) => def.push_back(term),
None => return Err(Error::InvalidWord),
}
}

if let Some(Word(name)) = def.pop_front() {
if let Some(Term::Word(name)) = def.pop_front() {
self.store_word(name, def)
} else {
Err(Error::InvalidWord)
Expand Down