$25
Extending a Programming Language: Functions
For this assignment we will be extending SBML to include function definitions and function calls.
We will use continue to use the parser generator PLY – Python Lex and Yacc – to specify and implement the SBML language.
SBML extension:
Function Definition:
A function definition begins with the keyword "fun", followed by the name of the function, a left parenthesis, variables representing formal parameters separated by commas, a right parenthesis, an equal sign, a block, and then an expression.
When the function is called, the block is executed first. Then the expression is evaluated and the result of the expression evaluation is returned to the caller.
Function Call:
A function call is an expression. The function name is followed by a left parenthesis, and then argument expressions, followed by a right parenthesis.
The number of arguments passed to the call must match the number of parameters in the function definition.
General Requirements:
An input program might contain multiple function definitions followed by a single main block that gets executed.
You will have to implement a stack to create the scoping for local variables inside recursive function calls.
Call by value will be used to pass arguments to parameters.
Two example programs with functions are given below.
Example SBML Input Programs:
Example1:
fun factorial(n) =
{
if (n < 1)
{
output = 1;
} else {
output = n * factorial(n - 1);
} } output; {
print(factorial(3));
}
Test and output should look like this: $ python sbml.py example1
Example2: fun gcd(a, b) = { t = b; b = a mod b; if (b == 0) { output = t; } else {
output = gcd(t, b);
} } output; {
print(gcd(32, 18));
}
Test and output should look like this: $ python sbml.py example1