Add a new implementation in rust

This commit is contained in:
Alexandre Stein 2022-11-12 19:06:52 +01:00
parent fa33d861be
commit a1075277be
4 changed files with 97 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
rust-calc/target

7
rust-calc/Cargo.lock generated Normal file
View File

@ -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"

8
rust-calc/Cargo.toml Normal file
View File

@ -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]

81
rust-calc/src/main.rs Normal file
View File

@ -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;
}
}