Z
Z
Zakharov Alexander2018-06-07 21:54:44
C++ / C#
Zakharov Alexander, 2018-06-07 21:54:44

Get textual representation of formula written in code back to text?

Hello.
The code contains many formulas of the form (30 pieces and will be replenished, the work has just begun, the use of functions is not provided, but there can be all sorts of mathematical formulas like SQRT, ABS, etc.):
_Weight_rostv = OTSTUP_SVAYA_MIN_B * 2 + (D_SVAYA + 1000) + D_SVAYA ;
_Weight_rostv = OTSTUP_SVAYA_MIN_B * 2 + D_SVAYA * 3 + D_SVAYA;
you need to use these expressions in three ways
1. Getting the result (what it already is in itself)
2. Converting the expression to the right of equals into a text string (just like it is written in the code, you can without spaces)
3. Ideal - outputting the expression with parameter substitution (replace variables with their values).
The sequence of the solution is not important, i.e. if you can come up with some 4th option and get all three from it - it is also being considered.
Is it possible to?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
VoidVolker, 2018-06-07
@VoidVolker

Something like this:

public static void Main(string[] args)
{
    var cube = new Formula<Func<int, int>>( (x) => x * x, "(x) => x * x" );
    Console.WriteLine(cube.Exec(3));
    Console.WriteLine(cube.Text);
}

public class Formula<T>
{
    public readonly T Exec;
    public readonly string Text;
    public Formula(T action, string text)
    {
        Exec = action;
        Text = text;
    }                    
}

A
Alexander, 2018-06-07
@NeiroNx

It is necessary to dig towards DataBinder.Eval from the System.Web.UI package:

E
eRKa, 2018-06-08
@kttotto

There will be a lot of brackets, but if this option suits

static void Main(string[] args)
{
  Expression<Func<double, double, double>> exp = (OTSTUP_SVAYA_MIN_B, D_SVAYA) => (OTSTUP_SVAYA_MIN_B * 2 + D_SVAYA * 3 + D_SVAYA);
  var expBody = ((LambdaExpression)exp).Body.ToString();

  Console.WriteLine(expBody);

  double _OTSTUP_SVAYA_MIN_B = 1;
  double _D_SVAYA = 2;

  var expBodyWithParams = expBody.Replace("OTSTUP_SVAYA_MIN_B", _OTSTUP_SVAYA_MIN_B.ToString()).Replace("D_SVAYA", _D_SVAYA.ToString());

  Console.WriteLine(expBodyWithParams);
  Console.ReadKey();
}

If you bang extra brackets, then the expBody tree must be traversed independently recursively and build a string to your liking.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question