/** * Try calculating the current expression * @returns current expression (calculated) or "ERROR" string if something went wrong */ public string Result() { string result = ""; try { // Explicitly handle factorials because `Evaluate` method has no operand for them. string parsed_result = EvaluateUnknownFactorials(this.ExpressionCurrent); result = CalculatorLogic.Evaluate(parsed_result).ToString(); this.ExpressionCurrent = result; } catch (Exception) { this.ClearCurrent(); result = "ERROR"; } // By returning the result and cleaning the inner memory is how we // achieve the lazy displaying of the result while still "clearing" // the screen once new numbers get pressed //this.ClearCurrent(); return(result); }
public MainWindow() { InitializeComponent(); this.calculatorLogic = new CalculatorLogic(); // Bind the display widgets to the appropriate handler this.display = new DisplayLogic(textDisplayPrevious, textDisplayExpression, textDisplayResult); }
/** * Find every factorial in a substring and evaluate it. Works recursevly. * Once the factorial has been evaluated -> replace the expression in * the input string with the calculated value, return the altered string. * * @returns Expression where all factorials have been evaluted */ private static string EvaluateUnknownFactorials(string expression) { Match match = FACTORTIAL_TOKEN.Match(expression); CaptureCollection captures = match.Captures; foreach (Capture capture in captures) { // remove the '!' with the substring // Perform recursive check for other factorials string group_substring = EvaluateUnknownFactorials(capture.Value.Substring(0, capture.Value.Length - 1)); long localResult = (long)CalculatorLogic.Evaluate(group_substring); long localResultFact = CalculatorLogic.Factorial(localResult); expression = DirtyReplace(expression, localResultFact.ToString(), capture.Value, capture.Index); } // Sanity check for making sure that no factorials are left. The need for this extra check can be // eliminated if unittests are created to prove that such construction has no need return(expression.Contains("!") ? EvaluateUnknownFactorials(expression) : expression); }