Add a new implementation in rust
This commit is contained in:
parent
fa33d861be
commit
a1075277be
|
@ -0,0 +1 @@
|
|||
rust-calc/target
|
|
@ -0,0 +1,7 @@
|
|||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "rust-calc"
|
||||
version = "0.1.0"
|
|
@ -0,0 +1,8 @@
|
|||
[package]
|
||||
name = "rust-calc"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
|
@ -0,0 +1,81 @@
|
|||
use std::process;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Symbol {
|
||||
Minus,
|
||||
Plus,
|
||||
Multiply,
|
||||
Divide,
|
||||
}
|
||||
|
||||
struct TmpNum {
|
||||
s: String,
|
||||
}
|
||||
impl TmpNum {
|
||||
pub fn new() -> Self {
|
||||
Self { s: String::new() }
|
||||
}
|
||||
fn push(&mut self, c: char) {
|
||||
self.s.push(c);
|
||||
}
|
||||
fn get(&mut self) -> f32 {
|
||||
let n = self.s.parse::<f32>().ok().expect("number is malformed");
|
||||
self.s = String::new();
|
||||
|
||||
n
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(pattern: String) -> (Vec<Symbol>, Vec<f32>) {
|
||||
let mut symbols = Vec::new();
|
||||
let mut numbers = Vec::new();
|
||||
|
||||
let mut number = TmpNum::new();
|
||||
|
||||
for c in pattern.chars() {
|
||||
let s: Option<Symbol> = match c {
|
||||
'-' => Some(Symbol::Minus),
|
||||
'+' => Some(Symbol::Plus),
|
||||
'*' => Some(Symbol::Multiply),
|
||||
'/' => Some(Symbol::Divide),
|
||||
|
||||
_ => None,
|
||||
};
|
||||
|
||||
match s {
|
||||
Some(s) => {
|
||||
symbols.push(s);
|
||||
numbers.push(number.get());
|
||||
}
|
||||
None => {
|
||||
number.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
numbers.push(number.get());
|
||||
|
||||
(symbols, numbers)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let pattern = match std::env::args().nth(1) {
|
||||
None => {
|
||||
println!("Input must be provided");
|
||||
process::exit(1)
|
||||
}
|
||||
Some(s) => s,
|
||||
};
|
||||
|
||||
let (symbols, numbers) = parse(pattern);
|
||||
|
||||
println!("{:?}", symbols);
|
||||
println!("{:?}", numbers);
|
||||
|
||||
let mut counter = 0;
|
||||
let mut n1 = numbers.get(0).expect("expect at least the first value");
|
||||
while counter < symbols.len() {
|
||||
let mut n2 = numbers.get(counter+1).expect("expect at least a second value");
|
||||
counter +=1;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue