Skip to content

Instantly share code, notes, and snippets.

/playground.rs
Created Sep 25, 2017

Embed
What would you like to do?
Rust code shared from the playground
type Oper = fn(isize, isize) -> isize;
pub struct WordProblem(&'static str);
impl WordProblem {
pub fn new(command: &'static str) -> Self {
WordProblem(command)
}
pub fn answer(&self) -> Result<isize, ()> {
let tokens: Vec<_> = self.0
.split(|c: char| !c.is_alphanumeric())
.collect();
let operator_plus = |a: isize, b: isize| -> isize { return a + b } as Oper;
let operator_minus = |a: isize, b: isize| -> isize { return a - b } as Oper;
let operator_multiply = |a: isize, b: isize| -> isize { return a * b } as Oper;
let operator_divide = |a: isize, b: isize| -> isize { return a / b } as Oper;
let mut accum = 0;
let mut operator_func: &Oper = &operator_plus;
for token in tokens {
if let Ok(num) = token.parse::<isize>() {
accum = operator_func(accum, num);
} else {
match token {
"plus" => operator_func = &operator_plus,
"minus" => operator_func = &operator_minus,
"multiplied" => operator_func = &operator_multiply,
"divided" => operator_func = &operator_divide,
_ => return Err(()),
}
}
}
Ok(accum)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.