PHP code example of hoa-math-community / math
1. Go to this page and download the library: Download hoa-math-community/math library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hoa-math-community / math example snippets
// 1. Load the compiler.
$compiler = Hoa\Compiler\Llk::load(
new Hoa\File\Read('hoa://Library/Math/Arithmetic.pp')
);
// 2. Load the visitor, aka the “evaluator”.
$visitor = new Hoa\Math\Visitor\Arithmetic();
// 3. Declare the expression.
$expression = '1 / 2 / 3 + 4 * (5 * 2 - 6) * PI / avg(7, 8, 9)';
// 4. Parse the expression.
$ast = $compiler->parse($expression);
// 5. Evaluate.
var_dump(
$visitor->visit($ast)
);
/**
* Will output:
* float(6.4498519738463)
*/
// Bonus. Print the AST of the expression.
$dump = new Hoa\Compiler\Visitor\Dump();
echo $dump->visit($ast);
/**
* Will output:
* > #addition
* > > #division
* > > > token(number, 1)
* > > > #division
* > > > > token(number, 2)
* > > > > token(number, 3)
* > > #multiplication
* > > > token(number, 4)
* > > > #multiplication
* > > > > #group
* > > > > > #substraction
* > > > > > > #multiplication
* > > > > > > > token(number, 5)
* > > > > > > > token(number, 2)
* > > > > > > token(number, 6)
* > > > > #division
* > > > > > token(constant, PI)
* > > > > > #function
* > > > > > > token(id, avg)
* > > > > > > token(number, 7)
* > > > > > > token(number, 8)
* > > > > > > token(number, 9)
*/
$visitor->addFunction('rand', function ($min, $max) {
return mt_rand($min, $max);
});
$visitor->addConstant('ANSWER', 42);
$expression = 'rand(ANSWER / 2, ANSWER * 2)'
var_dump(
$visitor->visit($compiler->parse($expression))
);
/**
* Could output:
* int(53)
*/