0

I want to parse and calculate formulas line by line. The formulas depend on the given variables x1 and x2. The number of formulas per line is not fixed, and there are dependencies between the results of the formulas, but the nesting level does not exceed two layers. I hope to calculate the final result y.

Here is some simulated data:

x1 = [1, 2, 3]
x2 = [4, 5, 6]
fml = ["y1=x1+x2; y2 = x1-x2; y=y1*y2", "y1=x1+x2; y2=x1-x2; y=y1*y2", "y1=x1+x2; y=y1+1"]
t = table(x1, x2, fml)

Output Results

I tried to implement it by concatenating scripts, but there are issues.

s = "x1=" + string(t.x1) + "; " + "x2=" + string(t.x2) + "; " + t.fml + "; " + "y;"

runScript(s[0]) // OK
each(runScript, s) // returns [NULL, NULL, NULL]

Why does it work when executed separately, but not when iterating with each?

Or is it possible to achieve this through metaprogramming?

1 Answer 1

-1

Here's a solution that should work for your use case. The implementation uses metaprogramming to parse and evaluate the formulas row by row:

def parseFomula(row){
    tmp = row.fml.strReplace(" ", "").split(";").split("=")
    d = dict(tmp[0], tmp[1])
    re = each(parseExpr{,row}, d).eval:E()
    last = tmp.tail()[0]
    re = parseExpr(d[last], re).eval()
    return re
}
each(parseFomula, t)

For each row, first remove spaces and split the formula string by semicolons and equals signs to extract variable assignments. Then create a dictionary mapping intermediate variables (like y1, y2) to their corresponding expressions. After that, use parseExpr and eval to compute the values of all intermediate variables while making the row data available in the evaluation context. Finally extract and compute the final variable (typically y) from the last assignment.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.