Skip to content

Instantly share code, notes, and snippets.

Created September 25, 2017 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/eb3a5fdeabdd4b6aba100dc003ef17bb to your computer and use it in GitHub Desktop.
Save anonymous/eb3a5fdeabdd4b6aba100dc003ef17bb to your computer and use it in GitHub Desktop.
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