Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confirming Greenspun's 10th Law in C#

I am trying to implement an infrastructure in C# that would allow me to make arbitrary mathematical expressions. For example, I want to be able to take an expression like

asin(sqrt(z - sin(x+y)^2))

and turn it into an object that will allow me to evaluate it in terms of x,y, and z, get derivatives, and possibly do some kind of symbolic algebra on it. What are people's thoughts on a good model for this in C#?

I have my own take, which I am afraid is heading off into architecture astronautics, so I want to make sure that is not the case.

Basically, the functions like sin, +, sqrt, etc. have classes based off a base class:

Function

Function<TOut> : Function
    TOut Value

Function<Tin, TOut> : Function
    TOut Evaluate(TIn value)
    Function Derivative
    Function<TOut, TIn> INverse

Function<TInA, TInB, TOut> : Function
    TOut Evaluate(TInA valueA, TInB valueB)
    Function PartialDerivativeA
    Function PartialDerivativeB

So far, so simple. The trick is how to compose the functions. Here I believe I want something like a currying approach so that I can evaluate the function for a single parameter, and have the other ones remain. So I am thinking of having a factory class like this:

Function<TInA, TInB, TOut> -> 
           Function<TInA, Function<TInB, TOut>>

(Function<TInA, TInB, TOut>, Function<TInX, TInA>, null) -> 
           Function<TInX, Function<TInB, TOut>>

(Function<TInA, TInB, TOut>, Function<TInA>, Function<TInX, TInY, TInB>) -> 
           Function<TInX, Function<TInY, TInB>>

and so on. My main concerns are that the generic types might make the system unusable (if the user is required to know the full generic types just to evaluate), and that I might not be able to construct all of the generic types from the input arguments.

Thanks for your input!

like image 906
reveazure Avatar asked Nov 14 '22 13:11

reveazure


1 Answers

Note that it is possible to use the C# compiler to evaluate expressions.

Evaluating Mathematical Expressions by Compiling C# Code at Runtime http://www.codeproject.com/KB/recipes/matheval.aspx

like image 91
Robert Harvey Avatar answered Dec 17 '22 11:12

Robert Harvey