Assume that the plus operation is defined for integers and that it requires both
ID: 3913948 • Letter: A
Question
Assume that the plus operation is defined for integers and that it requires both operands to be integer. The return type will be integer if type checking succeeds. Complete the type checking code below:
class Expr {
abstract Type getType();
abstract void setType(Type);
static Type intType() { ... } // returns unified int type static
Type errType() { ... } // returns error type
static boolean isIntType(Type t) { ... } // true iff t is int
}
class Plus extends Expr {
Expr getLeftOperand() { ... }
Expr getRightOperand() { ... }
}
void typeCheck(Plus op) {
/? YOUR CODE ?/
op.setType( /? result type, or error type if type checking fails ?/);
}
Explanation / Answer
void typeCheck(Plus op){
Expr leftOp = op.getLeftOperand();
Expr rightOp = op.getRightOperand();
bool ifLeftInt = op.isIntType( leftOp.getType() );
bool ifRightInt = op.isIntType( rightOp.getType() );
if( ifLeftInt && ifRightInt ){
op.setType( op.intType() );
} else{
op.setType( op.errType() );
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.