Re: Parse string expression and get result

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Arne Vajhøj wrote:
wannabe geek wrote:
I need a way to successfully parse a string expression and return a number. Some examples:
"1+1" = 2
"3+4*2" = 11
"(11*(8-3))/5" = 11
"X*2" = X*2
"If((1=1)=True,1,2)" = 1
"Sum(X,3,5)+Max(1,2,3)" = X+11

I am thinking about creating a function plotter and the user must be able to create complex functions. I need to be able to use 'X' as a parameter. I also need the ablility to use any number of custom functions. I will probably be using only boolean and numeric (double perhaps?) values. I can foresee no need for comments. Could somebody guide me to a webpage that is straightforward and easy to follow? I would appreciate something quite efficient since this will be iterating quite a few times.

You can make some rather sophisticated parsers or you
can be plain lazy and decide on C# syntax and dynamicly
generate some C# code and call that.

Example:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Reflection;
using System.CodeDom.Compiler;

using Microsoft.CSharp;

namespace E
{
public interface IFuncEval
{
double Eval(double x);
}
public class FuncEvalFactory
{
private static int n = 0;
private static Dictionary<string,IFuncEval> m = new Dictionary<string,IFuncEval>();
public static IFuncEval Create(string expr)
{
IFuncEval o = null;
if(m.ContainsKey(expr))
{
o = m[expr];
}
else
{
n++;
string cn = "FuncEval_" + n;
string src = "using System;" +
"using E;" +
"" +
"public class " + cn + " : IFuncEval" +
"{" +
" public double Eval(double x)" +
" {" +
" return " + expr + ";" +
" }" +
"}";
CodeDomProvider comp = new CSharpCodeProvider();
CompilerParameters param = new CompilerParameters();
param.GenerateInMemory = true;
param.ReferencedAssemblies.Add("System.dll");

param.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
CompilerResults res = comp.CompileAssemblyFromSource(param, src);
Assembly asm = res.CompiledAssembly;
o = (IFuncEval)asm.CreateInstance(cn);
m.Add(expr, o);
}
return o;
}
}
public class MainClass
{
public static void Test(string expr)
{
Console.WriteLine(expr + ":");
IFuncEval f = FuncEvalFactory.Create(expr);
for(int i = -2; i <= 2; i++)
{
Console.WriteLine(" " + i + " -> " + f.Eval(i));
}
}
public static void Main(string[] args)
{
Test("2*x*x-3*x+4");
Test("Math.Exp(Math.Sqrt(x+2))");
Console.ReadKey();
}
}
}

Arne
.



Relevant Pages

  • Re: evaluating expressions
    ... string src = "import System; import E; public class C ... CompilerParameters param = new CompilerParameters; ... public static double Eval(string expr) ...
    (microsoft.public.dotnet.languages.csharp)
  • Proof of Randomness
    ... public class HelloWorld { ... public static void main{ ... Object) and initializes it by calling the constructor. ... the interpreter skips to "catch" to see what it should do. ...
    (sci.math)
  • Re: Multithreading - writing to same file C#
    ... > to log the response of the DAL methods and log ... > public class yyy ... > private Mutex mut = new Mutex; ... > public static void Main ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Is it possible to "decipher" Java serialization data?
    ... that saved a class called "UserInfo". ... public class save { ... public static void main{ ... public String getUserName() { ...
    (comp.lang.java.programmer)
  • Spawned process output
    ... public static void main ... StreamConsumer errFromProcess ... public class StreamConsumer extends Thread ... while (!isDone) ...
    (comp.lang.java.programmer)