Junior — Senior
Conversion of AST of an arithmetic expression into a string representation of code
livecode
Task condition
Given: an arithmetic expression represented as an AST (Abstract Syntax Tree) in prefix notation.
The AST can be either a floating-point number or an array where the first element is always a string representing an arithmetic operation, and the subsequent elements are its arguments (also in the form of AST):
AST = float | ['operation', operand1, operand2, ..., operandN], where operand1, operand2, ... are ASTs.
Supported operations:
- unary minus (-)
- unary plus (+)
- addition (+)
- subtraction (-)
- multiplication (*)
- division (/).
It can be assumed that the input data is always correct.
You need to implement the function astToCode that takes an AST and returns a string with the equivalent code.
function astToCode(array|float $node): string
{
// implementation of transformation
}
function test(array|float $node, string $expected): void
{
$actual = astToCode($node);
echo $actual === $expected ? 'OK' : "FAIL ";
echo ": $expected" . PHP_EOL;
}
test(5, '5');
test([['+', 1, 2], '-', 3]], '-(+1 2)');
test(['+', -1], '+(-1)');
test([['*', 1, 2], '*', [ '-', 3, 1]], '(1 * 2) * (3 - 1)');
test([[['*', 2, 5], '*', 7], '/', ['-', 8, ['+', 5, 6]]]], '2 * 5 * 7 / (8 - (5 + 6))');
test([['+', 1, 2], '-', ['-', 3, 4], '-', ['+', 5, 6]],], '1 + 2 - (3 - 4) - (5 + 6)');