SlideShare a Scribd company logo
1 of 8
Download to read offline
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

Similar to Rust Infix to Postfix

Assume an infix expression can only contain five operators, + .pdf
Assume an infix expression can only contain five operators,    + .pdfAssume an infix expression can only contain five operators,    + .pdf
Assume an infix expression can only contain five operators, + .pdfmarketing413921
 
1.4 expression tree
1.4 expression tree  1.4 expression tree
1.4 expression tree Krish_ver2
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manualnikshaikh786
 
Infix postfixcoversion
Infix postfixcoversionInfix postfixcoversion
Infix postfixcoversionPdr Patnaik
 
java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfarjuntelecom26
 
stack-111104232459-phpapp02.pdf
stack-111104232459-phpapp02.pdfstack-111104232459-phpapp02.pdf
stack-111104232459-phpapp02.pdfKalpana Mohan
 
Infix-Postfix expression conversion
Infix-Postfix expression conversionInfix-Postfix expression conversion
Infix-Postfix expression conversionRashmiranja625
 
Infix to Postfix Conversion.pdf
Infix to Postfix Conversion.pdfInfix to Postfix Conversion.pdf
Infix to Postfix Conversion.pdfayushi296420
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxKALPANAC20
 
Please need help on C++ language.Infix to Postfix) Write a program.pdf
Please need help on C++ language.Infix to Postfix) Write a program.pdfPlease need help on C++ language.Infix to Postfix) Write a program.pdf
Please need help on C++ language.Infix to Postfix) Write a program.pdfpristiegee
 
Applicationofstack by Ali F.RAshid
Applicationofstack  by Ali F.RAshid Applicationofstack  by Ali F.RAshid
Applicationofstack by Ali F.RAshid ali rashid
 
Application of Stack - Yadraj Meena
Application of Stack - Yadraj MeenaApplication of Stack - Yadraj Meena
Application of Stack - Yadraj MeenaDipayan Sarkar
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURESUsha Mahalingam
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-listpinakspatel
 
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdfC++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdfrahulfancycorner21
 
Unit 2 application of stack
Unit 2  application of stack Unit 2  application of stack
Unit 2 application of stack LavanyaJ28
 

Similar to Rust Infix to Postfix (20)

Assume an infix expression can only contain five operators, + .pdf
Assume an infix expression can only contain five operators,    + .pdfAssume an infix expression can only contain five operators,    + .pdf
Assume an infix expression can only contain five operators, + .pdf
 
1.4 expression tree
1.4 expression tree  1.4 expression tree
1.4 expression tree
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
 
Infix postfixcoversion
Infix postfixcoversionInfix postfixcoversion
Infix postfixcoversion
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdf
 
stack-111104232459-phpapp02.pdf
stack-111104232459-phpapp02.pdfstack-111104232459-phpapp02.pdf
stack-111104232459-phpapp02.pdf
 
Infix-Postfix expression conversion
Infix-Postfix expression conversionInfix-Postfix expression conversion
Infix-Postfix expression conversion
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Infix to Postfix Conversion.pdf
Infix to Postfix Conversion.pdfInfix to Postfix Conversion.pdf
Infix to Postfix Conversion.pdf
 
Stack
StackStack
Stack
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
 
Please need help on C++ language.Infix to Postfix) Write a program.pdf
Please need help on C++ language.Infix to Postfix) Write a program.pdfPlease need help on C++ language.Infix to Postfix) Write a program.pdf
Please need help on C++ language.Infix to Postfix) Write a program.pdf
 
Applicationofstack by Ali F.RAshid
Applicationofstack  by Ali F.RAshid Applicationofstack  by Ali F.RAshid
Applicationofstack by Ali F.RAshid
 
Application of Stack - Yadraj Meena
Application of Stack - Yadraj MeenaApplication of Stack - Yadraj Meena
Application of Stack - Yadraj Meena
 
Unit II - LINEAR DATA STRUCTURES
Unit II -  LINEAR DATA STRUCTURESUnit II -  LINEAR DATA STRUCTURES
Unit II - LINEAR DATA STRUCTURES
 
Stacks,queues,linked-list
Stacks,queues,linked-listStacks,queues,linked-list
Stacks,queues,linked-list
 
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdfC++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
 
Unit 2 application of stack
Unit 2  application of stack Unit 2  application of stack
Unit 2 application of stack
 

More from deepaksatrker

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

More from deepaksatrker (20)

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

Recently uploaded

Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 

Recently uploaded (20)

Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 

Rust Infix to Postfix

  • 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])) } }