Python – Data Structures to represent logical expressions

data structureslogic-programmingpython

Here is a logical statement:

term1 AND (term2 OR term3) OR term4

What is an effective way of storing this information in a data structure?

For example, should I use a graph, with a property on each edge defining the operator to the next term? (This suggestion doesn't make sense IMO, but it's a data structure that might be useful for this)

Best Answer

I used an object graph to code something similar before. Each object in the graph has its own structure.

For example:

BinaryLogicalExpression : BooleanExpression
{
  Left : BooleanExpression
  Right : BooleanExpression
  Operator : BinaryLogicalOperator
}
ArithmeticExpression : Expression
{
  Left : Expression
  Right : Expression
  Operator : ArithmeticOperator
}
// for modelling brackets...
LogicalGroupExpression : BooleanExpression
{
  GroupedExpression : BooleanExpression
}
// to hold constant values...
IntegerConstant : Expression
{
  Value : int
}
StringConstant : Expression
{
  Value : string
}

I'd then use a series of Visitor implementations to traverse the object graph for evaluation and processing of the expression.

Expression
{
  Accept(ExpressionVisitor visitor);
}

ExpressionVisitor
{
  Visit(BinaryLogicalExpression e);
  Visit(ArithmeticExpression e);
  Visit(StringConstant e);
  Visit(IntegerConstant e);
  etc...
}

Using an object graph and Visitor makes it easy to serialize such expressions to XML or similar hierarchical data structure.