In this article series, I would like to look at how Mathos Parser (a very simple expression parser) can be used to perform things that were not originally intended. Today, I am going to show what has to be done to make Mathos Parser able to interpret factorial notation, such as “4!

Already in the parser, we can solve this in at least two different ways:

  • creating a localFunction fact() that will take one parameter and return the factorial of that number
  • using FactorialPower(falling power) instead, that is 4!4 would be 24 and 4!1=4.

Both methods do not require you to change anything in the input string, but they might not be as close to the mathematical notation as we want it to be. Therefore, as a part of this article, I am going to illustrate the changes in the input string that have to be made, to make it understand 4!.

  1. Include Reg Ex name space as following:
    using System.Text.RegularExpressions;
  2. Add these two methods somewhere in the class:
    static decimal factorial(decimal x)
    {
        if(x==1 || x== 0)
        {
            return 1;
        }
        else
        {
            return x * factorial(x - 1);
        }
    }
    
    static string FactorialString(Match m)
    {
        return m.Value + "0";
    }
  3. Define the Mathos Parser and add a definition of the factorial operator including the way it should be executed. Note, at this stage, for this to work, the factorial number has to be in the form of 4!0 or 4!1 ((both result in 24).
    Mathos.Parser.MathParser parser = new Mathos.Parser.MathParser();
    
    parser.OperatorList = new List<string>() {"!" ,"%","^", "/", "*",  "-", "+"}; // removed ":" for division
    parser.OperatorAction.Add("!", (x, y) => factorial(x));
  4. Before the input string can be parsed, perform the following action (assuming you have defined a variable input with a value):
    input = Regex.Replace(input, @"[0-9]+\!", new MatchEvaluator(FactorialString));
  5. Parser the string and store the result:
    decimal result = parser.Parse(input);

This is how we can make Mathos Parser able to understand mathematical notation of factorial. In the next article of this series, we are going to look at how Mathos Parser can be used to construct a new programming language.