/** a literal translation of the Scheme symbolic derivative code.
 *  See DerivVisitor for a more object-oriented coding.
 */
public class Deriv {
    public static Expression deriv(Expression exp, String var) {
        if (exp instanceof NumericLiteral) {
            return new NumericLiteral(0.0);
        } else if (exp instanceof Variable) {
            return new NumericLiteral(((Variable)exp).same(var) ? 1.0 : 0.0);
        } else if (exp instanceof Sum) {
            return new Sum(deriv(((Sum)exp).addend(), var),
                           deriv(((Sum)exp).augend(), var));
        } else { // (exp instanceof Product)
            return new Sum(new Product(deriv(((Product)exp).multiplier(),
                                             var),
                                       ((Product)exp).multiplicand()),
                           new Product(((Product)exp).multiplier(),
                                       deriv(((Product)exp).multiplicand(),
                                             var)));
        }
    }
}
