arthanzel/evaluatex

Get equation's unknown variables

Closed this issue · 2 comments

Given an equation string like "x^2 + y", I need to find out the list of its unknown variables such as ["x", "y"] in this example. I feel this is something already being done somewhere in evaluatex code, but I couldn't find a public function or the correspondent internal code. This function should work with any valid evaluatex expression. Is that something useful to add to the interface? If not, could you point me out the file where I can find this logic so I can abstract that in my codebase?

Thank you for this suggestion!

When you compile a string into a function, the resulting function has a few handy fields like ast and tokens that allow you to inspect the compiled function's intermediate representations. Evaluatex replaces known named variables at compile-time in the lexer and retains the remaining unknown variables as "symbol" tokens. You could define a function, or perhaps contribute a method on the compiled function here that scans through the token list, filters token.type === Token.TYPE_SYMBOL, and collects unique token.value. This should list the names of unknown variables. Something like:

new Set(evaluatex("2x+y+y")
  .tokens
  .filter(t => t.type === "SYMBOL")
  .map(t => t.value)
)
// => Set { 'x', 'y' }

For compatibility reasons, a PR for this should use regular loops instead of filter/map and an object instead of Set to eliminate duplicates.

Perhaps the documentation should also be amended to reflect the availability of ast, tokens, and expression members on the compiled function.

I tried what you suggested in my codebase and it worked alright! Thank you! I am not sure if I should PR it since it is such a simple function once you know about tokens. I concur it would be helpful to refer to the ast, tokens and expression fields in the documentation.