Arithmetica.Tokenization.Rewriting.NegationRewriter.Rewrite C# (CSharp) Метод

Rewrite() публичный Метод

public Rewrite ( TokenStream tokens ) : TokenStream
tokens TokenStream
Результат TokenStream
        public override TokenStream Rewrite(TokenStream tokens)
        {
            // Token stream needs to be in infix notation.
            if (tokens.Notation != TokenNotation.Infix)
            {
                throw new MathExpressionException("Token stream is not in infix notation.");
            }

            List<Token> result = new List<Token>();
            for (int index = 0; index < tokens.Count; index++)
            {
                Token token = tokens[index];

                if (token.Type == TokenType.Subtraction)
                {
                    // Is this the first token?
                    if (index == 0)
                    {
                        // Replace this token with a negation.
                        result.Add(new Token(TokenType.Negation, "-"));
                    }
                    // Previous token an operator?
                    else if (index > 0 && tokens[index - 1].IsOperator())
                    {
                        // Replace this token with a negation.
                        result.Add(new Token(TokenType.Negation, "-"));
                    }
                    // Previous token an opening parenthesis.
                    else if (index > 0 && tokens[index - 1].Type == TokenType.OpeningParenthesis)
                    {
                        // Replace this token with a negation.
                        result.Add(new Token(TokenType.Negation, "-"));
                    }
                    else
                    {
                        result.Add(token);
                    }
                }
                else
                {
                    result.Add(token);
                }
            }
            return new TokenStream(result, TokenNotation.Infix);
        }

Usage Example

 public void NegationRewriter_TokenStream_Needs_To_Be_In_Infix_Notation()
 {
     TokenStream stream = new TokenStream(Enumerable.Empty<Token>(), TokenNotation.Postfix);
     NegationRewriter rewriter = new NegationRewriter();
     var exception = Assert.Throws<MathExpressionException>(() => rewriter.Rewrite(stream));
     Assert.AreEqual("Token stream is not in infix notation.", exception.Message);
 }
NegationRewriter