public void Parse(RawExpression rawExpression) { RawExpressionParser parser = new RawExpressionParser(rawExpression); IEnumerable <RawMultiplier> rawMultipliers = parser.Iterator(); foreach (RawMultiplier rawMultiplier in rawMultipliers) { Multiplier multiplier = new Multiplier(rawMultiplier); Expression expression = multiplier.ConvertToExpression(); this.Join(expression); } }
/** * Main magic is happening here */ public string Normalize(string equation) { string[] parts = equation.Split(new char[] { '=' }); Expression parsedEquation; Multiplier rightPart; if (parts.Length != 2) { return("Equation is incorrect, it should have two parts and equal sign"); } string leftPartRaw = parts[0]; // get left part string rightPartRaw = "(" + parts[1] + ")"; // and right part int rightOffset = equation.IndexOf('=') + 1; try { // parse left part as an Expression parsedEquation = new Expression(new RawExpression(0, leftPartRaw)); } catch (ParseException e) { // parse right part as Multiplier as we want eventually multiply it to -1 return(this.HandleException(equation, e)); } try { rightPart = new Multiplier(new RawMultiplier(rightOffset, rightPartRaw, -1)); } catch (ParseException e) { return(this.HandleException(equation, e)); } // If I wrote it in Python I would very likely use PyParser package which make life // a way easier for parsing expressions like this, but I decided to go hardcore // and write it on C# for which breaf search didn't get result of analogues of // PyParse in .NET world. So I simply wrote my own parsers // then join left part expression and converted multiplier to expression parsedEquation.Join(rightPart.ConvertToExpression()); // do sorting List <Summand> sortedSummands = this.Sort(parsedEquation.summands); return(this.GenerateEquationString(sortedSummands)); }