simple_cli_calculator/
lib.rs1#[derive(Debug, PartialEq)]
8pub enum Operations {
10 Add,
11 Subtract,
12 Multiply,
13 Divide,
14 Power,
15}
16
17pub struct Calculation {
19 pub num1: f64,
20 pub num2: f64,
21 pub operation: Operations,
22}
23
24impl Calculation {
25 pub fn from_string(input: &str) -> Result<Self, &str> {
39 let mut inputstring = input.split_whitespace();
40
41 let num1: f64 = match inputstring.next() {
42 Some(num) => match num.parse::<f64>() {
43 Ok(res) => res,
44 Err(_) => return Err("First number is invalid."),
45 },
46 _ => return Err("Input a Number."),
47 };
48
49 let operator: char = match inputstring.next() {
50 Some(char) => match char.char_indices().next() {
51 Some((_f, char)) => char,
52 None => {
53 return Err(
54 "If you're seeing this, i have no clue, let the author know what u typed.",
55 );
56 }
57 },
58 _ => return Err("Input an operator."),
59 };
60
61 let num2: f64 = match inputstring.next() {
62 Some(num) => match num.parse::<f64>() {
63 Ok(res) => res,
64 Err(_) => return Err("Second number is invalid."),
65 },
66 _ => return Err("Input a second number."),
67 };
68
69 Self::new(num1, num2, operator)
70 }
71
72 pub fn from_rpn(input: &str) -> Result<Self, &str> {
73 let mut inputstring = input.split_whitespace();
74
75 let num1: f64 = match inputstring.next() {
76 Some(num) => match num.parse::<f64>() {
77 Ok(res) => res,
78 Err(_) => return Err("First number is invalid."),
79 },
80 _ => return Err("Input a Number."),
81 };
82
83 let num2: f64 = match inputstring.next() {
84 Some(num) => match num.parse::<f64>() {
85 Ok(res) => res,
86 Err(_) => return Err("Second number is invalid."),
87 },
88 _ => return Err("Input a second number."),
89 };
90
91 let operator: char = match inputstring.next() {
92 Some(char) => match char.char_indices().next() {
93 Some((_f, char)) => char,
94 None => {
95 return Err(
96 "If you're seeing this, i have no clue, let the author know what u typed.",
97 );
98 }
99 },
100 _ => return Err("Input an operator."),
101 };
102
103 Self::new(num1, num2, operator)
104 }
105
106 pub fn new(num1: f64, num2: f64, op: char) -> Result<Self, &'static str> {
107 Ok(Calculation {
108 num1,
109 num2,
110 operation: match op {
111 '+' => Operations::Add,
112 '-' => Operations::Subtract,
113 '*' => Operations::Multiply,
114 '/' => Operations::Divide,
115 '^' => Operations::Power,
116 _ => return Err("Unknown operation, try + - * / ^"),
117 },
118 })
119 }
120
121 pub fn calculate_result(&self) -> f64 {
122 match self.operation {
123 Operations::Add => self.num1 + self.num2,
124 Operations::Divide => self.num1 / self.num2,
125 Operations::Multiply => self.num1 * self.num2,
126 Operations::Power => self.num1.powf(self.num2),
127 Operations::Subtract => self.num1 - self.num2,
128 }
129 }
130}