SlideShare a Scribd company logo
Using Rust
Because postfix expressions are simpler and faster to evaluate, compilers transform infix
expressions in source programs to postfix expressions in executable programs. You will
implement this transformation.
## Infix expressions
An infix expression contains one or more of the following tokens:
* Operands: integers, such as `1`, `-23`.
* Operators: arithmetic operators `+`, `-`, `*`, and `/` with their normal association and
precedence.
* Left and right parentheses.
A valid infix expression must satisfy all the following rules:
* An operand or left parenthesis cannot be preceded by an operand or right parenthesis.
* An operator or right parenthesis cannot
* be the first token in the expression, or
* be preceded by an operator or left parenthesis.
* An operator or left parenthesis cannot be the last token in the expression.
* Each left parenthesis must match a unique right parenthesis, and vice versa.
## Transform infix to postfix expression
1. Create a stack.
2. Scan the tokens in the infix expression.
* If the token is an operand, output it.
* If the token is a left parenthesis, push it onto the stack.
* If the token is a right parenthesis, pop and output all the operators from the stack until
encountering a left parenthesis. Pop and discard the left parenthesis.
* If the token is an operator
* If the stack is empty, push the token onto the stack.
* Otherwise, if the top of the stack is an operator and its precedence is greater than or equal to
the precedence of the token, pop and output the operator from the stack, and repeat this process.
Finally, push the token in the infix expression onto the stack.
3. Pop and output all the remaining tokens on the stack.
## Public API
Your program must provide the following public API.
```
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Operator {
// `+`
Add,
// `-`
Sub,
// `*`
Mul,
// `/`
Div,
}
#[derive(Debug, PartialEq)]
pub enum InfixToken {
Operator(Operator),
Operand(isize),
LeftParen,
RightParen,
}
#[derive(Debug, PartialEq)]
pub enum PostfixToken {
Operator(Operator),
Operand(isize),
}
/// Transforms an infix expression to a postfix expression.
///
/// If the infix expression is valid, outputs `Some(_)`;
/// otherwise, outputs `None`.
pub fn infix_to_postfix(tokens: &[InfixToken]) -> Option> {
unimplemented!();
}
Solution
#[derive(Clone, Copy, Debug, PartialEq)] pub enum Operator { // `+` Add, // `-` Sub,
// `*` Mul, // `/` Div, } #[derive(Debug, PartialEq)] pub enum InfixToken {
Operator(Operator), Operand(isize), LeftParen, RightParen, } #[derive(Debug,
PartialEq)] pub enum PostfixToken { Operator(Operator), Operand(isize), } /// Transforms
an infix expression to a postfix expression. /// /// If the infix expression is valid, outputs
`Some(_)`; /// otherwise, outputs `None`. pub fn infix_to_postfix(tokens: &[InfixToken]) ->
Option> { let mut stack: Vec = vec![]; let mut output: Vec = vec![];
////////////////////////////////// VALIDATION /////////////////////////////////////////////////// let mut
right_paren = 0; let mut left_paren = 0; for token in tokens{ if token ==
&InfixToken::RightParen{ right_paren+=1; } if token ==
&InfixToken::LeftParen{ left_paren+=1; } } if right_paren != left_paren {
return None; } if tokens[0] == InfixToken::RightParen{ return None; } if
tokens[0] == InfixToken::Operator(Operator::Add){ return None; } if tokens[0] ==
InfixToken::Operator(Operator::Sub){ return None; } if tokens[0] ==
InfixToken::Operator(Operator::Mul){ return None; } if tokens[0] ==
InfixToken::Operator(Operator::Div){ return None; } if tokens[tokens.len()-1] ==
InfixToken::LeftParen{ return None; } if tokens[tokens.len()-1] ==
InfixToken::Operator(Operator::Add){ return None; } if tokens[tokens.len()-1] ==
InfixToken::Operator(Operator::Sub){ return None; } if tokens[tokens.len()-1] ==
InfixToken::Operator(Operator::Mul){ return None; } if tokens[tokens.len()-1] ==
InfixToken::Operator(Operator::Div){ return None; } let mut index = 0; while index
!= tokens.len()-1{ if tokens[index] == InfixToken::RightParen && tokens[index+1] ==
InfixToken::LeftParen{ return None; } index += 1; }
let mut index = 0; while index != tokens.len()-1{ let ref k = tokens[index];
match k{ &InfixToken::Operand(x) => { if tokens[index+1]
== InfixToken::Operand(x){ return None; }
if tokens[index+1] == InfixToken::LeftParen{ return None;
} }
&InfixToken::Operator(operator) => { if tokens[index+1] ==
InfixToken::Operator(operator){ return None; }
if tokens[index+1] == InfixToken::RightParen{ return
None; } } &InfixToken::LeftParen => {
if tokens[index+1] == InfixToken::RightParen{ return
None; } } _ => {}, }
index += 1; } let mut index = 1; while index != tokens.len(){ let ref k =
tokens[index]; match k{ &InfixToken::Operand(x) => {
if tokens[index-1] == InfixToken::RightParen{
return None; } } &InfixToken::Operator(x) =>
{ if tokens[index-1] == InfixToken::LeftParen{
return None; } } _ => {}, }
index += 1; }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
for token in tokens{ match token{ &InfixToken::Operand(x) =>
output.push(PostfixToken::Operand(x)), &InfixToken::LeftParen =>
stack.push(InfixToken::LeftParen), &InfixToken::RightParen =>
{ loop{ let y = stack.pop().unwrap();
match y{ InfixToken::Operator(y) =>
output.push(PostfixToken::Operator(y)), InfixToken::LeftParen =>
break, InfixToken::RightParen => break,
InfixToken::Operand(x) => break, } }
}, &InfixToken::Operator(Operator::Add) => {
if stack.len() == 0{
stack.push(InfixToken::Operator(Operator::Add)); }
//////////////////////////////////////////////// else{ loop{
if stack.len() == 0{ break;
} let z = stack.pop().unwrap();
match z{
InfixToken::Operator(Operator::Add) => {
output.push(PostfixToken::Operator(Operator::Add));
//stack.push(InfixToken::Operator(Operator::Add)); },
InfixToken::Operator(Operator::Sub) => {
output.push(PostfixToken::Operator(Operator::Sub));
//stack.push(InfixToken::Operator(Operator::Add)); },
InfixToken::Operator(Operator::Mul) => {
output.push(PostfixToken::Operator(Operator::Mul));
//stack.push(InfixToken::Operator(Operator::Add)); }
InfixToken::Operator(Operator::Div) => {
output.push(PostfixToken::Operator(Operator::Div));
//stack.push(InfixToken::Operator(Operator::Add)); },
InfixToken::LeftParen => {
stack.push(InfixToken::LeftParen);
//stack.push(InfixToken::Operator(Operator::Add)); break;
} InfixToken::RightParen => {
stack.push(InfixToken::RightParen);
//stack.push(InfixToken::Operator(Operator::Add)); break;
} _ => {},
} }
stack.push(InfixToken::Operator(Operator::Add));
} ///////////////////////////////////////////////////////////////// },
&InfixToken::Operator(Operator::Sub) => { if stack.len() == 0{
stack.push(InfixToken::Operator(Operator::Sub)); }
//////////////////////////////////////////////// else{ loop{
if stack.len() == 0{ break;
} let z = stack.pop().unwrap();
match z{ InfixToken::Operator(Operator::Add) => {
output.push(PostfixToken::Operator(Operator::Add));
//stack.push(InfixToken::Operator(Operator::Sub));
}, InfixToken::Operator(Operator::Sub) => {
output.push(PostfixToken::Operator(Operator::Sub));
//stack.push(InfixToken::Operator(Operator::Sub)); },
InfixToken::Operator(Operator::Mul) => {
output.push(PostfixToken::Operator(Operator::Mul));
//stack.push(InfixToken::Operator(Operator::Sub)); }
InfixToken::Operator(Operator::Div) => {
output.push(PostfixToken::Operator(Operator::Div));
//stack.push(InfixToken::Operator(Operator::Sub)); },
InfixToken::LeftParen => {
stack.push(InfixToken::LeftParen);
//stack.push(InfixToken::Operator(Operator::Sub)); break;
} InfixToken::RightParen => {
stack.push(InfixToken::RightParen);
//stack.push(InfixToken::Operator(Operator::Sub)); break;
} _ => {},
} }
stack.push(InfixToken::Operator(Operator::Sub));
} ///////////////////////////////////////////////////////////////// },
&InfixToken::Operator(Operator::Mul) => { if stack.len() == 0{
stack.push(InfixToken::Operator(Operator::Mul)); }
//////////////////////////////////////////////// else{ loop{
if stack.len() == 0{ break;
} let z = stack.pop().unwrap();
match z{ InfixToken::Operator(Operator::Add) => {
stack.push(InfixToken::Operator(Operator::Add));
//stack.push(InfixToken::Operator(Operator::Mul));
break; }
InfixToken::Operator(Operator::Sub) => {
stack.push(InfixToken::Operator(Operator::Sub));
//stack.push(InfixToken::Operator(Operator::Mul)); break;
} InfixToken::Operator(Operator::Mul)
=> { output.push(PostfixToken::Operator(Operator::Mul));
//stack.push(InfixToken::Operator(Operator::Mul));
} InfixToken::Operator(Operator::Div) => {
output.push(PostfixToken::Operator(Operator::Div));
//stack.push(InfixToken::Operator(Operator::Mul));
} InfixToken::LeftParen => {
stack.push(InfixToken::LeftParen);
//stack.push(InfixToken::Operator(Operator::Mul)); break;
} InfixToken::RightParen => {
stack.push(InfixToken::RightParen);
//stack.push(InfixToken::Operator(Operator::Mul)); break;
} _ => {},
} }
stack.push(InfixToken::Operator(Operator::Mul));
} ///////////////////////////////////////////////////////////////// },
&InfixToken::Operator(Operator::Div) => { if stack.len() == 0{
stack.push(InfixToken::Operator(Operator::Div)); }
//////////////////////////////////////////////// else{ loop{
if stack.len() == 0{ break;
} let z = stack.pop().unwrap();
match z{ InfixToken::Operator(Operator::Add) => {
stack.push(InfixToken::Operator(Operator::Add));
//stack.push(InfixToken::Operator(Operator::Div));
break; }
InfixToken::Operator(Operator::Sub) => {
stack.push(InfixToken::Operator(Operator::Sub));
//stack.push(InfixToken::Operator(Operator::Div)); break;
} InfixToken::Operator(Operator::Mul)
=> { output.push(PostfixToken::Operator(Operator::Mul))
},
InfixToken::Operator(Operator::Div) => {
output.push(PostfixToken::Operator(Operator::Div)) },
InfixToken::LeftParen => {
stack.push(InfixToken::LeftParen);
//stack.push(InfixToken::Operator(Operator::Div)); break;
} InfixToken::RightParen => {
stack.push(InfixToken::RightParen);
//stack.push(InfixToken::Operator(Operator::Div)); break;
} _ => {},
} }
stack.push(InfixToken::Operator(Operator::Div));
} ///////////////////////////////////////////////////////////////// }, } } while
stack.len() != 0{ let x = stack.pop().unwrap(); match x{
InfixToken::Operator(x) => output.push(PostfixToken::Operator(x)), _ => {},//return
None,//////////////////////////////////////////////////////////////////////////////// } } return
Some(output); } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { let v:
Vec =
vec![PostfixToken::Operand(2),PostfixToken::Operand(3),PostfixToken::Operator(Operator::Ad
d)]; assert_eq!(Some(v),
infix_to_postfix(&[InfixToken::Operand(2),InfixToken::Operator(Operator::Add),InfixToken::O
perand(3)])) } #[test] fn it_works1() { let v: Vec =
vec![PostfixToken::Operand(2),PostfixToken::Operand(3),PostfixToken::Operator(Operator::Ad
d),PostfixToken::Operand(1),PostfixToken::Operator(Operator::Sub)]; assert_eq!(Some(v),
infix_to_postfix(&[InfixToken::LeftParen,InfixToken::Operand(2),InfixToken::Operator(Operat
or::Add),InfixToken::Operand(3),InfixToken::RightParen,InfixToken::Operator(Operator::Sub),I
nfixToken::Operand(1)])) } #[test] fn it_works2() { let v: Vec =
vec![PostfixToken::Operand(2),PostfixToken::Operand(3),PostfixToken::Operator(Operator::Ad
d),PostfixToken::Operand(2),PostfixToken::Operand(1),PostfixToken::Operator(Operator::Add),
PostfixToken::Operator(Operator::Sub)]; assert_eq!(Some(v),
infix_to_postfix(&[InfixToken::LeftParen,InfixToken::Operand(2),InfixToken::Operator(Operat
or::Add),InfixToken::Operand(3),InfixToken::RightParen,InfixToken::Operator(Operator::Sub),I
nfixToken::LeftParen,InfixToken::Operand(2),InfixToken::Operator(Operator::Add),InfixToken:
:Operand(1),InfixToken::RightParen])) } }

More Related Content

PPTX
Prefix, Infix and Post-fix Notations
PDF
1.3- infix-ti-postfix.pdf
PPT
data structure and algorithm by bomboat_3
PPTX
week9-prefixinfixandpostfixnotations-191013065821.pptx
PDF
2. Stack. Write a program that uses the stack class (you can use.pdf
PPTX
conversion of Infix to Postfix conversion using stack
PPTX
My lecture infix-to-postfix
PPTX
DSA_chapter_04_Stack and data structure and Queue.pptx
Prefix, Infix and Post-fix Notations
1.3- infix-ti-postfix.pdf
data structure and algorithm by bomboat_3
week9-prefixinfixandpostfixnotations-191013065821.pptx
2. Stack. Write a program that uses the stack class (you can use.pdf
conversion of Infix to Postfix conversion using stack
My lecture infix-to-postfix
DSA_chapter_04_Stack and data structure and Queue.pptx

Similar to Using RustBecause postfix expressions are simpler and faster to ev.pdf (20)

PPT
PDF
Infix to Prefix (Conversion, Evaluation, Code)
PPT
Expression evaluation
PPTX
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
PDF
Applications of Stack
PPTX
Infix postfixcoversion
PPT
MO 2020 DS Stacks 3 AB.ppt
PDF
Please need help on C++ language.Infix to Postfix) Write a program.pdf
PDF
Write a program that converts an infix expression into an equivalent.pdf
PPTX
DS MOD2 (1) (1).pptx
PDF
The concept of stack is extremely important in computer science and .pdf
PPTX
STACK APPLICATIONS: INFOX TO POSTFIX CONVERSION AND EVALUATION OF POSTFIX EXP...
PPT
Infix prefix postfix
PPTX
Infix-Postfix expression conversion
PDF
Ds stack 03
PPTX
5.stack
PPTX
2.2 stack applications Infix to Postfix & Evaluation of Post Fix
PPTX
Conversion of Infix to postfix.pptxjjjjj
PDF
Data structure lab manual
PPT
infixToPostfixConversion example.ppt
Infix to Prefix (Conversion, Evaluation, Code)
Expression evaluation
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
Applications of Stack
Infix postfixcoversion
MO 2020 DS Stacks 3 AB.ppt
Please need help on C++ language.Infix to Postfix) Write a program.pdf
Write a program that converts an infix expression into an equivalent.pdf
DS MOD2 (1) (1).pptx
The concept of stack is extremely important in computer science and .pdf
STACK APPLICATIONS: INFOX TO POSTFIX CONVERSION AND EVALUATION OF POSTFIX EXP...
Infix prefix postfix
Infix-Postfix expression conversion
Ds stack 03
5.stack
2.2 stack applications Infix to Postfix & Evaluation of Post Fix
Conversion of Infix to postfix.pptxjjjjj
Data structure lab manual
infixToPostfixConversion example.ppt
Ad

More from deepaksatrker (20)

PDF
Develop an encryption and decryption algorithm Your program should a.pdf
PDF
Cystic fibrosis is caused by a recessive mutant allele (cf). Two norm.pdf
PDF
Compute the addition and multiplication of the following 2 binary fl.pdf
PDF
BIOCHEMList and briefly describe the six types of the 6 basic rec.pdf
PDF
Write an audit memo that explains how quality control for an audit e.pdf
PDF
What legal impacts did the ACA have on tax-exempt hospitalsSolu.pdf
PDF
Which members of the family above are afflicted with Huntingtons Di.pdf
PDF
What could be the arguments of a production functionA Cost and La.pdf
PDF
What are the benefits to firms of international diversification Wha.pdf
PDF
What are electromagnetic wavesSolutionWe are encompassed by w.pdf
PDF
tnt en Assignment Nickele Company reoorts net income of sae,4n0 in .pdf
PDF
This file contains a complete array-based MultiSet, but not the code.pdf
PDF
The structure of a high temperature superconductor containing barium.pdf
PDF
The present value o.pdf
PDF
The Associated Handles section in Resource Monitor can be used to sh.pdf
PDF
T 5. A contract should be held enforceable even if a party is mistake.pdf
PDF
Subject - Project ManagementDescribe what the WBS is and why you .pdf
PDF
Significant mass extinctions occurred during which of the following .pdf
PDF
SOLUTIONNotice thatt2becomes simpler when differentiated (wherease5t.pdf
PDF
Please help with the English test !!! Thank you very much!Identify.pdf
Develop an encryption and decryption algorithm Your program should a.pdf
Cystic fibrosis is caused by a recessive mutant allele (cf). Two norm.pdf
Compute the addition and multiplication of the following 2 binary fl.pdf
BIOCHEMList and briefly describe the six types of the 6 basic rec.pdf
Write an audit memo that explains how quality control for an audit e.pdf
What legal impacts did the ACA have on tax-exempt hospitalsSolu.pdf
Which members of the family above are afflicted with Huntingtons Di.pdf
What could be the arguments of a production functionA Cost and La.pdf
What are the benefits to firms of international diversification Wha.pdf
What are electromagnetic wavesSolutionWe are encompassed by w.pdf
tnt en Assignment Nickele Company reoorts net income of sae,4n0 in .pdf
This file contains a complete array-based MultiSet, but not the code.pdf
The structure of a high temperature superconductor containing barium.pdf
The present value o.pdf
The Associated Handles section in Resource Monitor can be used to sh.pdf
T 5. A contract should be held enforceable even if a party is mistake.pdf
Subject - Project ManagementDescribe what the WBS is and why you .pdf
Significant mass extinctions occurred during which of the following .pdf
SOLUTIONNotice thatt2becomes simpler when differentiated (wherease5t.pdf
Please help with the English test !!! Thank you very much!Identify.pdf
Ad

Recently uploaded (20)

PPTX
Lesson notes of climatology university.
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Institutional Correction lecture only . . .
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
GDM (1) (1).pptx small presentation for students
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
01-Introduction-to-Information-Management.pdf
PDF
Computing-Curriculum for Schools in Ghana
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
Lesson notes of climatology university.
Anesthesia in Laparoscopic Surgery in India
Abdominal Access Techniques with Prof. Dr. R K Mishra
Sports Quiz easy sports quiz sports quiz
Pharma ospi slides which help in ospi learning
Institutional Correction lecture only . . .
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Renaissance Architecture: A Journey from Faith to Humanism
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
GDM (1) (1).pptx small presentation for students
TR - Agricultural Crops Production NC III.pdf
01-Introduction-to-Information-Management.pdf
Computing-Curriculum for Schools in Ghana
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Cell Types and Its function , kingdom of life
Supply Chain Operations Speaking Notes -ICLT Program
O7-L3 Supply Chain Operations - ICLT Program
PPH.pptx obstetrics and gynecology in nursing
STATICS OF THE RIGID BODIES Hibbelers.pdf

Using RustBecause postfix expressions are simpler and faster to ev.pdf

  • 1. Using Rust Because postfix expressions are simpler and faster to evaluate, compilers transform infix expressions in source programs to postfix expressions in executable programs. You will implement this transformation. ## Infix expressions An infix expression contains one or more of the following tokens: * Operands: integers, such as `1`, `-23`. * Operators: arithmetic operators `+`, `-`, `*`, and `/` with their normal association and precedence. * Left and right parentheses. A valid infix expression must satisfy all the following rules: * An operand or left parenthesis cannot be preceded by an operand or right parenthesis. * An operator or right parenthesis cannot * be the first token in the expression, or * be preceded by an operator or left parenthesis. * An operator or left parenthesis cannot be the last token in the expression. * Each left parenthesis must match a unique right parenthesis, and vice versa. ## Transform infix to postfix expression 1. Create a stack. 2. Scan the tokens in the infix expression. * If the token is an operand, output it. * If the token is a left parenthesis, push it onto the stack. * If the token is a right parenthesis, pop and output all the operators from the stack until encountering a left parenthesis. Pop and discard the left parenthesis. * If the token is an operator * If the stack is empty, push the token onto the stack. * Otherwise, if the top of the stack is an operator and its precedence is greater than or equal to
  • 2. the precedence of the token, pop and output the operator from the stack, and repeat this process. Finally, push the token in the infix expression onto the stack. 3. Pop and output all the remaining tokens on the stack. ## Public API Your program must provide the following public API. ``` #[derive(Clone, Copy, Debug, PartialEq)] pub enum Operator { // `+` Add, // `-` Sub, // `*` Mul, // `/` Div, } #[derive(Debug, PartialEq)] pub enum InfixToken { Operator(Operator), Operand(isize), LeftParen, RightParen, } #[derive(Debug, PartialEq)] pub enum PostfixToken { Operator(Operator), Operand(isize), } /// Transforms an infix expression to a postfix expression.
  • 3. /// /// If the infix expression is valid, outputs `Some(_)`; /// otherwise, outputs `None`. pub fn infix_to_postfix(tokens: &[InfixToken]) -> Option> { unimplemented!(); } Solution #[derive(Clone, Copy, Debug, PartialEq)] pub enum Operator { // `+` Add, // `-` Sub, // `*` Mul, // `/` Div, } #[derive(Debug, PartialEq)] pub enum InfixToken { Operator(Operator), Operand(isize), LeftParen, RightParen, } #[derive(Debug, PartialEq)] pub enum PostfixToken { Operator(Operator), Operand(isize), } /// Transforms an infix expression to a postfix expression. /// /// If the infix expression is valid, outputs `Some(_)`; /// otherwise, outputs `None`. pub fn infix_to_postfix(tokens: &[InfixToken]) -> Option> { let mut stack: Vec = vec![]; let mut output: Vec = vec![]; ////////////////////////////////// VALIDATION /////////////////////////////////////////////////// let mut right_paren = 0; let mut left_paren = 0; for token in tokens{ if token == &InfixToken::RightParen{ right_paren+=1; } if token == &InfixToken::LeftParen{ left_paren+=1; } } if right_paren != left_paren { return None; } if tokens[0] == InfixToken::RightParen{ return None; } if tokens[0] == InfixToken::Operator(Operator::Add){ return None; } if tokens[0] == InfixToken::Operator(Operator::Sub){ return None; } if tokens[0] == InfixToken::Operator(Operator::Mul){ return None; } if tokens[0] == InfixToken::Operator(Operator::Div){ return None; } if tokens[tokens.len()-1] == InfixToken::LeftParen{ return None; } if tokens[tokens.len()-1] == InfixToken::Operator(Operator::Add){ return None; } if tokens[tokens.len()-1] == InfixToken::Operator(Operator::Sub){ return None; } if tokens[tokens.len()-1] == InfixToken::Operator(Operator::Mul){ return None; } if tokens[tokens.len()-1] == InfixToken::Operator(Operator::Div){ return None; } let mut index = 0; while index != tokens.len()-1{ if tokens[index] == InfixToken::RightParen && tokens[index+1] == InfixToken::LeftParen{ return None; } index += 1; } let mut index = 0; while index != tokens.len()-1{ let ref k = tokens[index]; match k{ &InfixToken::Operand(x) => { if tokens[index+1] == InfixToken::Operand(x){ return None; } if tokens[index+1] == InfixToken::LeftParen{ return None; } }
  • 4. &InfixToken::Operator(operator) => { if tokens[index+1] == InfixToken::Operator(operator){ return None; } if tokens[index+1] == InfixToken::RightParen{ return None; } } &InfixToken::LeftParen => { if tokens[index+1] == InfixToken::RightParen{ return None; } } _ => {}, } index += 1; } let mut index = 1; while index != tokens.len(){ let ref k = tokens[index]; match k{ &InfixToken::Operand(x) => { if tokens[index-1] == InfixToken::RightParen{ return None; } } &InfixToken::Operator(x) => { if tokens[index-1] == InfixToken::LeftParen{ return None; } } _ => {}, } index += 1; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// for token in tokens{ match token{ &InfixToken::Operand(x) => output.push(PostfixToken::Operand(x)), &InfixToken::LeftParen => stack.push(InfixToken::LeftParen), &InfixToken::RightParen => { loop{ let y = stack.pop().unwrap(); match y{ InfixToken::Operator(y) => output.push(PostfixToken::Operator(y)), InfixToken::LeftParen => break, InfixToken::RightParen => break, InfixToken::Operand(x) => break, } } }, &InfixToken::Operator(Operator::Add) => { if stack.len() == 0{ stack.push(InfixToken::Operator(Operator::Add)); } //////////////////////////////////////////////// else{ loop{ if stack.len() == 0{ break; } let z = stack.pop().unwrap(); match z{ InfixToken::Operator(Operator::Add) => { output.push(PostfixToken::Operator(Operator::Add)); //stack.push(InfixToken::Operator(Operator::Add)); }, InfixToken::Operator(Operator::Sub) => { output.push(PostfixToken::Operator(Operator::Sub)); //stack.push(InfixToken::Operator(Operator::Add)); }, InfixToken::Operator(Operator::Mul) => {
  • 5. output.push(PostfixToken::Operator(Operator::Mul)); //stack.push(InfixToken::Operator(Operator::Add)); } InfixToken::Operator(Operator::Div) => { output.push(PostfixToken::Operator(Operator::Div)); //stack.push(InfixToken::Operator(Operator::Add)); }, InfixToken::LeftParen => { stack.push(InfixToken::LeftParen); //stack.push(InfixToken::Operator(Operator::Add)); break; } InfixToken::RightParen => { stack.push(InfixToken::RightParen); //stack.push(InfixToken::Operator(Operator::Add)); break; } _ => {}, } } stack.push(InfixToken::Operator(Operator::Add)); } ///////////////////////////////////////////////////////////////// }, &InfixToken::Operator(Operator::Sub) => { if stack.len() == 0{ stack.push(InfixToken::Operator(Operator::Sub)); } //////////////////////////////////////////////// else{ loop{ if stack.len() == 0{ break; } let z = stack.pop().unwrap(); match z{ InfixToken::Operator(Operator::Add) => { output.push(PostfixToken::Operator(Operator::Add)); //stack.push(InfixToken::Operator(Operator::Sub)); }, InfixToken::Operator(Operator::Sub) => { output.push(PostfixToken::Operator(Operator::Sub)); //stack.push(InfixToken::Operator(Operator::Sub)); }, InfixToken::Operator(Operator::Mul) => { output.push(PostfixToken::Operator(Operator::Mul)); //stack.push(InfixToken::Operator(Operator::Sub)); } InfixToken::Operator(Operator::Div) => { output.push(PostfixToken::Operator(Operator::Div)); //stack.push(InfixToken::Operator(Operator::Sub)); }, InfixToken::LeftParen => { stack.push(InfixToken::LeftParen); //stack.push(InfixToken::Operator(Operator::Sub)); break; } InfixToken::RightParen => {
  • 6. stack.push(InfixToken::RightParen); //stack.push(InfixToken::Operator(Operator::Sub)); break; } _ => {}, } } stack.push(InfixToken::Operator(Operator::Sub)); } ///////////////////////////////////////////////////////////////// }, &InfixToken::Operator(Operator::Mul) => { if stack.len() == 0{ stack.push(InfixToken::Operator(Operator::Mul)); } //////////////////////////////////////////////// else{ loop{ if stack.len() == 0{ break; } let z = stack.pop().unwrap(); match z{ InfixToken::Operator(Operator::Add) => { stack.push(InfixToken::Operator(Operator::Add)); //stack.push(InfixToken::Operator(Operator::Mul)); break; } InfixToken::Operator(Operator::Sub) => { stack.push(InfixToken::Operator(Operator::Sub)); //stack.push(InfixToken::Operator(Operator::Mul)); break; } InfixToken::Operator(Operator::Mul) => { output.push(PostfixToken::Operator(Operator::Mul)); //stack.push(InfixToken::Operator(Operator::Mul)); } InfixToken::Operator(Operator::Div) => { output.push(PostfixToken::Operator(Operator::Div)); //stack.push(InfixToken::Operator(Operator::Mul)); } InfixToken::LeftParen => { stack.push(InfixToken::LeftParen); //stack.push(InfixToken::Operator(Operator::Mul)); break; } InfixToken::RightParen => { stack.push(InfixToken::RightParen); //stack.push(InfixToken::Operator(Operator::Mul)); break; } _ => {}, } } stack.push(InfixToken::Operator(Operator::Mul)); } ///////////////////////////////////////////////////////////////// }, &InfixToken::Operator(Operator::Div) => { if stack.len() == 0{ stack.push(InfixToken::Operator(Operator::Div)); }
  • 7. //////////////////////////////////////////////// else{ loop{ if stack.len() == 0{ break; } let z = stack.pop().unwrap(); match z{ InfixToken::Operator(Operator::Add) => { stack.push(InfixToken::Operator(Operator::Add)); //stack.push(InfixToken::Operator(Operator::Div)); break; } InfixToken::Operator(Operator::Sub) => { stack.push(InfixToken::Operator(Operator::Sub)); //stack.push(InfixToken::Operator(Operator::Div)); break; } InfixToken::Operator(Operator::Mul) => { output.push(PostfixToken::Operator(Operator::Mul)) }, InfixToken::Operator(Operator::Div) => { output.push(PostfixToken::Operator(Operator::Div)) }, InfixToken::LeftParen => { stack.push(InfixToken::LeftParen); //stack.push(InfixToken::Operator(Operator::Div)); break; } InfixToken::RightParen => { stack.push(InfixToken::RightParen); //stack.push(InfixToken::Operator(Operator::Div)); break; } _ => {}, } } stack.push(InfixToken::Operator(Operator::Div)); } ///////////////////////////////////////////////////////////////// }, } } while stack.len() != 0{ let x = stack.pop().unwrap(); match x{ InfixToken::Operator(x) => output.push(PostfixToken::Operator(x)), _ => {},//return None,//////////////////////////////////////////////////////////////////////////////// } } return Some(output); } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { let v: Vec = vec![PostfixToken::Operand(2),PostfixToken::Operand(3),PostfixToken::Operator(Operator::Ad d)]; assert_eq!(Some(v), infix_to_postfix(&[InfixToken::Operand(2),InfixToken::Operator(Operator::Add),InfixToken::O perand(3)])) } #[test] fn it_works1() { let v: Vec = vec![PostfixToken::Operand(2),PostfixToken::Operand(3),PostfixToken::Operator(Operator::Ad d),PostfixToken::Operand(1),PostfixToken::Operator(Operator::Sub)]; assert_eq!(Some(v),
  • 8. infix_to_postfix(&[InfixToken::LeftParen,InfixToken::Operand(2),InfixToken::Operator(Operat or::Add),InfixToken::Operand(3),InfixToken::RightParen,InfixToken::Operator(Operator::Sub),I nfixToken::Operand(1)])) } #[test] fn it_works2() { let v: Vec = vec![PostfixToken::Operand(2),PostfixToken::Operand(3),PostfixToken::Operator(Operator::Ad d),PostfixToken::Operand(2),PostfixToken::Operand(1),PostfixToken::Operator(Operator::Add), PostfixToken::Operator(Operator::Sub)]; assert_eq!(Some(v), infix_to_postfix(&[InfixToken::LeftParen,InfixToken::Operand(2),InfixToken::Operator(Operat or::Add),InfixToken::Operand(3),InfixToken::RightParen,InfixToken::Operator(Operator::Sub),I nfixToken::LeftParen,InfixToken::Operand(2),InfixToken::Operator(Operator::Add),InfixToken: :Operand(1),InfixToken::RightParen])) } }