The last two assignments for the quarter involve implementing a simple calculator in Ruby. This document specifies the input language for the calculator. The calculator allows the user to evaluate formulas involving floating-point values and the usual arithmetic operations, as well as to set and reference variables that can hold the results of these calculations.
A calculator program is specified by the following grammar..
program ::= statement | program statement
statement ::= exp | id=
exp |clear
id |list
|quit
|exit
exp ::= term | exp+
term | exp-
term
term ::= power | term*
power | term/
power
power ::= factor | factor**
power
factor ::= id | number |(
exp)
|sqrt
(
exp)
=
exp is executed by evaluating
the expression and binding that value to the given identifier. Any previous
value bound to that identifier is replaced. No output is printed.id not defined
is printed (with the actual identifier substituted for id)
and the value of the expression is not defined.
If an expression contains multiple occurrences of undefined identifiers,
the error message is printed for each occurrence of each undefined identifier.clear
id deletes the identifier from
the list of known (bound) identifiers.PI
is already defined
and is bound to 3.14159... (i.e., Math::PI
in Ruby). It may
be clear
ed or bound to a different value like any other identifier.list
causes all known identifiers to be printed
along with the values they are currently bound to. The order in which the
identifier, value pairs
are printed is not specified.quit
and exit
have the same effect.
Both terminate execution of the calculator.list
, clear
, quit
,
and exit
)
are reserved and may not be used as identifiers.
The built-in function name sqrt
also is reserved and cannot be used as an identifier.**
), which is right-associative.sqrt
function is the usual floating-point square root
function and is defined only on non-negative numbers.
The value of an expression that attempts to evaluate the square root
of a negative number is not defined.