In my earlier post "Some coding fun - The expression tree challenge :)" I showed an expression tree structure in F#, a functional first .NET language. Nobody picked up the gauntlet and gave an implementation in another language so I thought I would show the same functionality from an OO perspective instead of a functional one.
Again would be interesting to see this in another language like Python etc
In C# it made more sense to use inheritance of an abstract base. The parseTree function from the F# version has been replaced with virtual dispatch via the run method. I did ponder if it was worth adding an extra abstract base for the compuation style expressions but it gained nothing and just added more noise to the code.
public abstract class Expression
{
public abstract float Run();
}
public class Value : Expression
{
private float _value;
public Value(float value){_value = value;}
public override float Run() => _value;
}
public class Add : Expression
{
private Expression _lhs;
private Expression _rhs;
public Add(Expression lhs, Expression rhs)
{
_lhs = lhs;
_rhs = rhs;
}
public override float Run() => _lhs.Run() + _rhs.Run();
}
public class Subtract : Expression
{
private Expression _lhs;
private Expression _rhs;
public Subtract(Expression lhs, Expression rhs)
{
_lhs = lhs;
_rhs = rhs;
}
public override float Run() => _lhs.Run() - _rhs.Run();
}
public class Multiply : Expression
{
private Expression _lhs;
private Expression _rhs;
public Multiply(Expression lhs, Expression rhs)
{
_lhs = lhs;
_rhs = rhs;
}
public override float Run() => _lhs.Run() * _rhs.Run();
}
public class Divide : Expression
{
private Expression _lhs;
private Expression _rhs;
public Divide(Expression lhs, Expression rhs)
{
_lhs = lhs;
_rhs = rhs;
}
public override float Run() => _lhs.Run() / _rhs.Run();
}
var tree =
new Add(
new Value(5.0),
new Divide(new Value(3.0), new Value(1.5)));
var result = tree.Run();
For OO code it is not too bad but still many more lines of noise compared to the F# version.
Happy coding, hope I get some other examples this time :)
Woz