Imagine you have a function tree which has a number of nodes which can be either operator nodes (unary or binary operators), or terminal nodes (constants).
I’ve just started putting finger to keyboard and I’ve hit a small snag. I have created a Node interface, Operator:Node, BinaryOperator:Operator, UnaryOperator:Operator and Terminal:Node constructs.
And here I am with my problem. Do I now create a separate class for every foreseeable function? Do I create a SinOperator:UnaryOperator and CosOperator:UnaryOperator and AddOperator:BinaryOperator and so on? There are quite a few that can be considered if you include forward and inverse trig functions and their hyperbolic cousins.
Alternatively, I can just leave it at Binary and Unary operators and pass in a delegate which evaluates that node’s value based on it’s child nodes.
var sinOperator = new UnaryOperator(
childNode,
delegate()
{
return Math.Sin(childNode.GetValue());
});
But then there’s not really anything stopping me from putting all sorts of crazy stuff in the delegate, breaking the whole concept of it just being an operator.
Note: yes I realise that there are only a few operators (+-*/^√), and that sin/cos are actually functions… but for the purposes of this project we can assume that it is an operator
So how would you structure this in C#?
Why don’t you take a look at how Linq.Expressions work? It’s an existing model of this (and the whole .NET language) in C#.
Here you have a nice example of a Derivation program implemented using Linq.Expressions (You can check how it handles operators, sines, cosines, etc…)