Search code examples
c#oopalgebra

Represent algebraic expressions in an OOP language like C#


I am trying to represent algebra expressions such as polynomials and non-polynomials in C#. At the moment I have the following classes

class Variable {
    public char Var {get; set;}
    public int Exponent {get; set;}
...
}

class Term {
    public IList<Variable> {get; set;}
    public int CoEfficient {get; set;}
...
}

class Expression {
    public IList<Term> {get; set;}
...
}

This allows me to represent simple polynomials such as x^2+3x-8 but I want to be able to represent such expressions as (x+3)(x-2) and 3x(y+2). I have been trying to find out the terminology for this and I think the first is an expression '(x+3)(x-2)' containing two expressions 'x+3' and 'x-2' each containing two terms 'x', '3' and 'x', '-2'. The second is an expression '3x(y+2)' containing an expression 'y+2' multiplied by the term '3x' I was thinking that instead of a list of Terms in the Expression class it was a list of objects which are base classes of both Expression and Term and using recursion of some sort

How could I go about representing this in my classes?

I also want to be able to represent fractions and other non-polynomials

How would this fit into the picture?


Solution

  • Having a base class for expressions lets you build expressions out of other expressions.

    public abstract class BaseExpression
    {
    }
    
    public class VariableExpression : BaseExpression
    {
       public string Var {get; set;}
       public int Exponent {get; set;}
    }
    
    public class ConstExpression : BaseExpression
    {
       public object Val {get; set;}
    }
    
    public class BinExpression : BaseExpression
    {
       public BaseExpression Left { get; set; }
       public BaseExpression Right { get; set; }
       public string Operator { get; set; }
    }
    

    For example x(y-1) would be

    var xy_1 = new BinExpression()
    {
       Left  = new VariableExpression() { Var = "x" },
       Right = new BinExpression()
       {
           Left     = new VariableExpression() { Var = "y" },
           Right    = new ConstExpression() { Val = "1" },
           Operator = "-"
       },
       Operator = "*"
    }