Mathematics
parses a string, and evaluates it.
const OPS: [char; 4] = ['*', '/', '+', '-']; fn parse(operator: char, x: i32, y: i32) -> i32 { match operator { '+' => x + y, '-' => x - y, '*' => x * y, '/' => x / y, _ => 0 // handled } } fn calculator(text: &str) -> i32 { let text = text.replace(" ", ""); let index = text.find(OPS).unwrap(); let operator = text.as_bytes()[index] as char; let x = text.get(..index).unwrap().parse::<i32>().unwrap(); // unwrap hell let y = text.get(index+1..).unwrap().parse::<i32>().unwrap(); // more unwrap hell println!("{x} {operator} {y} is equal to {}", parse(operator, x, y)); return parse(operator, x, y); }
fn calculator(operator: char, num1: i32, num2: i32) -> i32 {- const OPS: [char; 4] = ['*', '/', '+', '-'];
- fn parse(operator: char, x: i32, y: i32) -> i32 {
- match operator {
'+' => num1 + num2,'-' => num1 - num2,'*' => num1 * num2,'/' => num1 / num2,_ => panic!("Invalid operator: '{operator}'.")- '+' => x + y, '-' => x - y,
- '*' => x * y, '/' => x / y,
- _ => 0 // handled
- }
- }
- fn calculator(text: &str) -> i32 {
- let text = text.replace(" ", "");
- let index = text.find(OPS).unwrap();
- let operator = text.as_bytes()[index] as char;
- let x = text.get(..index).unwrap().parse::<i32>().unwrap(); // unwrap hell
- let y = text.get(index+1..).unwrap().parse::<i32>().unwrap(); // more unwrap hell
- println!("{x} {operator} {y} is equal to {}", parse(operator, x, y));
- return parse(operator, x, y);
- }
// Add your tests here. // See https://doc.rust-lang.org/stable/rust-by-example/testing/unit_testing.html #[cfg(test)] mod tests { use super::*; #[test] fn test() { assert_eq!(calculator("8+4"), 12); assert_eq!(calculator("7 - 4"), 3); assert_eq!(calculator("7 * 8"), 56); assert_eq!(calculator("70 / 7"), 10); } }
- // Add your tests here.
- // See https://doc.rust-lang.org/stable/rust-by-example/testing/unit_testing.html
- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test() {
assert_eq!(calculator('+', 4, 8), 12);assert_eq!(calculator('-', 7, 4), 3);assert_eq!(calculator('*', 8, 7), 56);assert_eq!(calculator('/', 70, 7), 10);- assert_eq!(calculator("8+4"), 12);
- assert_eq!(calculator("7 - 4"), 3);
- assert_eq!(calculator("7 * 8"), 56);
- assert_eq!(calculator("70 / 7"), 10);
- }
- }