

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Material Type: Assignment; Class: Programming Languages; Subject: Computer Science; University: University of Texas - San Antonio; Term: Fall 2008;
Typology: Assignments
1 / 3
This page cannot be seen from the preview
Don't miss anything!


#include <stdio.h> typedef enum {TYPE_INT, TYPE_FLOAT} ValType; class AST { public: virtual ValType get_val_type() = 0; virtual void print() = 0; };
class Var : public AST { private: const char* name; ValType varType; // the declared type of variable public: Var(const char* _name, ValType _type) : name(_name), varType(_type) {} const char* get_name() { return name; } virtual ValType get_val_type() { return varType; } virtual void print() { if (varType == TYPE_INT) printf("%s : int\n", name); else printf("%s : float\n", name); } };
class Plus : public AST { private: AST opd1, opd2; public: Plus(AST _opd1, AST _opd2) : opd1(_opd1), opd2(_opd2) {} AST* get_opd1() { return opd1; } AST* get_opd2() { return opd2; } ValType get_type() { if (opd1->get_val_type() == TYPE_FLOAT ||
opd2->get_val_type() == TYPE_FLOAT) return TYPE_FLOAT; return TYPE_INT; } virtual ValType get_val_type() { return get_type(); } virtual void print() { opd1->print(); printf("+\n"); opd2->print(); } };
int main() { AST* res = new Plus( new Var("x1",TYPE_INT), new Var("y1", TYPE_FLOAT)); res->print(); }
(a) Draw a picture of the memory layout for the classes AST, Var, and Plus. (b) Draw a picture of the layout of the object res allocated within the main function. (c) The following is an alternative implementation of the above C++ classes in ML using function closures. datatype ValType = TYPE_INT | TYPE_FLOAT fun mk_Var(name,vartype) = let fun var_print() = if (vartype = TYPE_INT) then print(name ^ ": int\n") else print (name ^ ": float\n"); fun var_get_val_type() = vartype in { ast_print = var_print, get_val_type = var_get_val_type } end;
fun mk_Plus(opd1 : {ast_print:unit->unit,get_val_type:unit->ValType}, opd2 : {ast_print:unit->unit,get_val_type:unit->ValType}) = let fun plus_print() = (#ast_print(opd1)(); print "+\n"; #ast_print(opd2)()); fun plus_get_val_type() = if (#get_val_type(opd1)() = TYPE_FLOAT orelse #get_val_type(opd2)() = TYPE_FLOAT) then TYPE_FLOAT else TYPE_INT in { ast_print = plus_print, get_val_type = plus_get_val_type } end;
val res = mk_Plus( mk_Var("x1",TYPE_INT), mk_Var("y1", TYPE_FLOAT)); #ast_print(res)(); Draw a picture of the memory snapshot for ML code before making the last function call (hint: when drawing memory snapshort for functions, the only difference here is that the activation records of blocks are maintained via garbage