Reliable Software Logo

C++ In Action: Language

Exercises

  1. Create a top level Calculator object and make appropriate changes to lower level components.
  2. Add two new built in functions to the calculator, sqr and cube. Sqr squares its argument and cube cubes it (raises to the third power).
  3. Add the recognition of unary plus to the calculator. Make necessary modifications to the scanner and the parser. Add a new node, UPlusNode. The calculator should be able to deal correctly with such expressions as
    x = +2
    2 * + 7
    1 / (+1 - 2)
                        
  4. Add powers to the calculator according to the following productions
    Factor is SimpleFactor ^ Factor // a ^ b (a to the power of b)
    	or SimpleFactor
    
    SimpleFactor is ( Expression ) // parenthesized expression
    	or Number    // literal floating point number
    	or Identifier ( Expression )// function call
    	or Identifier// symbolic variable
    	or - Factor  // unary minus
  5. To all nodes in the parse tree add virtual method Print(). When Print() is called on the root of the tree, the whole tree should be displayed in some readable form. Use varying indentation (by printing a number of spaces at the beginning of every line) to distinguish between different levels of the tree. For instance
    void AddNode::Print (int indent) const
    {
        _pLeft->Print (indent + 2);
        Indent (indent);
        cout << "+" << endl;
        _pRight->Print (indent + 2);
        cout << endl;
    }
    
                        

    where Indent prints as many spaces as is the value of its argument.

  6. Derivatives of some of the built-in functions are, respectively
    sin(x) -> cos(x)
    cos(x) -> -sin(x)
    exp(x) -> exp(x)
    log(x) -> 1/x
    sqrt(x) -> 1/(2 * sqrt(x))
                        

    The derivative of a sum is a sum of derivatives, the derivative a product is given by the formula

    (f(x) * g(x))’ = f’(x) * g(x) + f(x) * g’(x)
                        

    where prime denotes a derivative. The derivative of a quotient is given by the formula

    (f(x) / g(x))’ = (f(x) * g’(x) - f’(x) * g(x)) / (g(x) * g(x))
                        

    and the derivative of the superposition of functions is given by

    (f(g(x))’ = g’(x) * f’(g(x)).
                        

    Rewrite the calculator to derive the symbolic derivative of the input by transforming the parse tree according to the formulas above. Make sure no memory is leaked in the process (that is, you must delete everything you allocate).

NextNext: Operator overloading