wordy: Extract example's functions out of WordProblem
No need to keep most of these as a struct since there's only one piece
of data being handled and one operation.
-#[derive(Debug, PartialEq)]
-struct WordProblem {
- command: String,
-}
-
#[derive(Debug, PartialEq)]
struct Token {
value: String,
@@ -26,18 +21,7 @@ impl Token {
}
pub fn answer(c: &str) -> Option<isize> {
- WordProblem::new(c).answer()
-}
-
-impl WordProblem {
- fn new(c: &str) -> Self {
- WordProblem {
- command: String::from(c),
- }
- }
-
- fn answer(&self) -> Option<isize> {
- let mut t = self.tokens();
+ let mut t = tokens(c);
let mut result: isize = 0;
let mut opr = "plus".to_string();
@@ -45,15 +29,15 @@ impl WordProblem {
None
} else {
while t.len() > 1 {
- result = self.evaluate(result, opr, self.operand(&t.remove(0)));
- opr = self.operator(&t.remove(0));
+ result = evaluate(result, opr, operand(&t.remove(0)));
+ opr = operator(&t.remove(0));
}
- result = self.evaluate(result, opr, self.operand(&t.remove(0)));
+ result = evaluate(result, opr, operand(&t.remove(0)));
Some(result)
}
}
- fn evaluate(&self, mut r: isize, operator: String, operand: isize) -> isize {
+fn evaluate(mut r: isize, operator: String, operand: isize) -> isize {
if operator == String::from("plus") {
r += operand;
r
@@ -71,16 +55,16 @@ impl WordProblem {
}
}
- fn operand(&self, t: &Token) -> isize {
+fn operand(t: &Token) -> isize {
t.value.parse().unwrap()
}
- fn operator(&self, t: &Token) -> String {
+fn operator(t: &Token) -> String {
String::from(t.value.clone())
}
- fn tokens(&self) -> Vec<Token> {
- self.command
+fn tokens(command: &str) -> Vec<Token> {
+ command
.split(|c: char| c.is_whitespace() || c == '?')
.map(|w| Token {
value: String::from(w),
@@ -88,4 +72,3 @@ impl WordProblem {
.filter(|t| t.is_valid())
.collect()
}
-}
