Created
September 25, 2017 09:20
-
-
Save anonymous/eb3a5fdeabdd4b6aba100dc003ef17bb to your computer and use it in GitHub Desktop.
Rust code shared from the playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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