Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a tool for parsing a string to create a C# func?

I need to know if there is any library out there that will allow me to, given a certain string representing a mathematical function, say, x^2+x+1, (don't care about how the string format, any will work for me) generates a C# func that will represent said function.

like image 840
user1432653 Avatar asked Dec 04 '22 03:12

user1432653


1 Answers

Been using FLEE (Fast Lightweight Expression Evaluator) for a while now and it's been working great. They have a version that maintains most functionality for Silverlight as well. It's designed to do pretty much exactly what you're asking for and more.

http://flee.codeplex.com/

Flee is an expression parser and evaluator for the .NET framework. It allows you to compute the value of string expressions such as sqrt(a^2 + b^2) at runtime. It uses a custom compiler, strongly-typed expression language, and lightweight codegen to compile expressions directly to IL. This means that expression evaluation is extremely fast and efficient.

Given your example from your comment to evaluate x^2+x+1 (written in Notepad):

public Func<double, double> CreateExpressionForX(string expression)
{

    ExpressionContext context = new ExpressionContext();
    // Define some variables
    context.Variables["x"] = 0.0d;

    // Use the variables in the expression
    IDynamicExpression e = context.CompileDynamic(expression);


    Func<double, double> expressionEvaluator = (double input) =>
    {
        content.Variables["x"] = input;
        var result = (double)e.Evaluate();
        return result;
    }

    return expressionEvaluator;
}



Func<double, double> expression = CreateExpressionForX("x^2 + x + 1");

double result1 = expression(1); //3
double result2 = expression(20.5); //441.75
double result3 = expression(-10.5); //121.75

Func<double, double> expression2 = CreateExpressionForX("3 * x + 10");

double result4 = expression2(1); //13
double result5 = expression2(20.5); //71.5
double result6 = expression2(-10.5); //-21.5
like image 101
Chris Sinclair Avatar answered Dec 28 '22 06:12

Chris Sinclair