Skip to content

Instantly share code, notes, and snippets.

Created September 25, 2017 09:05
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/de80b5162ace947d879b41d966f8ba4c to your computer and use it in GitHub Desktop.
Save anonymous/de80b5162ace947d879b41d966f8ba4c to your computer and use it in GitHub Desktop.
Rust code shared from the playground
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
.to_owned()
.split(|c: char| !c.is_alphanumeric())
.collect();
let operator_plus = Box::new(|a: isize, b: isize| -> isize { return a + b });
let operator_minus = Box::new(|a: isize, b: isize| -> isize { return a - b });
let operator_multiply = Box::new(|a: isize, b: isize| -> isize { return a * b });
let operator_divide = Box::new(|a: isize, b: isize| -> isize { return a / b });
let mut accum = 0;
let mut operator_func = &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