math-parser icon indicating copy to clipboard operation
math-parser copied to clipboard

How to evaluate custom functions inside expressions? (documentation)

Open koosvanderkolk opened this issue 4 years ago • 2 comments

I would like to run my own functions in evaluations. E.g.:

function doSomething($x) {
...
return $answer;
}
$AST = $parser->parse('doSomething(x)');
$evaluator->setVariables([ 'x' => 2 ]);
$value = $AST->accept($evaluator);

How to achieve this?

koosvanderkolk avatar Feb 03 '21 11:02 koosvanderkolk

I found class level comment in ComplexEvaluator class

 * ~~~
 *
 * TODO: handle user specified functions
 *
 */
class ComplexEvaluator implements Visitor

So looks like it's not implemented yet ;/

mszyca avatar Aug 18 '21 10:08 mszyca

If you know what functions you want to support, you can do this by creating your own custom versions of the Lexer and the Evaluator.

If you want to support arbitrary user-defined functions, there is currently no easy way to do that, but there might be in the next major upgrade. I'm working (somewhat infrequently) on refactoring some of the code to make it easier to extend the lexer and evaluator.

mossadal avatar Sep 02 '21 06:09 mossadal