parseExpr

Syntax

parseExpr(X, [varDict], [modules], [overloadedOperators])

Arguments

X is a string scalar/vector.

varDict is an optional parameter, which is a dictionary. If varDict is specified, while parsing by function eval , the variable in X will be parsed as the key of varDict. And the value of this variable is the value of varDict.

modules is an optional parameter which can be a string or an array of strings, indicating the name of the module to be loaded.

overloadedOperators is an optional parameter, which is a dictionary. The operators are mapped to a function. The key must be a string scalar, and the value must be a binary function.

Details

Convert string into metacode, which can be executed by function eval.

Examples

$ a=parseExpr("1+2")
$ a;
< 1 + 2 >

$ typestr(a);
CODE

$ a.eval();
3
$ t=table(1 2 3 4 as id, 5 6 7 8 as value, `IBM`MSFT`IBM`GOOG as name);

$ parseExpr("select * from t where name='IBM'").eval();

id

value

name

1

3

IBM

3

7

IBM

When function parseExpr parses variables, it first searches local variables, and then searches shared variables. It does not, however, search local variables within function definition.

def myfunc(){
    t3 = table(1..100 as id)
    return parseExpr("select * from t3 where id in 1..5").eval()
}

myfunc()

The script above produces the following error message:

myfunc() => myfunc: return ::evaluate(parseExpr("select * from t3 where id in 1..5")) => Can't find the object with name t3

For this issue, we can use function sql to dynamically generate SQL statements:

def myfunc(){
t3 = table(1..100 as id)
return sql(sqlCol("*"), t3, <id in 1..5>).eval()
}
myfunc();

id

1

2

3

4

5

Pass in the variables and values in the expression in the form of a dictionary, and assigning a value to the key of this dict is equivalent to assign a value to the variable.

$ d = dict(`a`b`c, (1, 2, 3))
$ parseExpr("a + b*c", d).eval()
7
$ d[`a] = 5;
$ parseExpr("a + b*c", d).eval()
11

The following example explains how to use functions in expressions. Because the variable “first” is not stored in dict, “first” is directly treated as a function when parsed.

$ index = [2000.01.01, 2000.01.31, 2000.02.15, 2000.02.20, 2000.03.12, 2000.04.16, 2000.05.06, 2000.08.30]
$ s = indexedSeries(index, 1..8)
$ d1 =  dict(STRING, ANY)
$ d1["S"] = s
$ parseExpr("resample(S, `M, first)", d1).eval()

Function add is defined in the test module under the modules directory. It is used to call the function in the module and map the binary operator “+” to a new function by specifying the parameter overloadedOperators at the same time. When the code is executed, the expression with operator “+” will be calculated according to the new definition.

$ parseExpr("test::add(1,2)+2", modules="test", overloadedOperators={"+": def(a, b){return a - b}}).eval()
1

Related functions: expr, eval