Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Use a functional language to traverse the following Abstract Syntax Tree. IN SCH

ID: 3865949 • Letter: U

Question

Use a functional language to traverse the following Abstract Syntax Tree. IN SCHEME LANGUAGE
'(program
((assign (var i int) (call (func getint void int) ()))
(assign (var j int) (call (func getint void int) ()))
(while (neq (var i int) (var j int))
((if (gt (var i int) (var j int))
((assign (var i int) (minus (var i int) (var j int))))
((assign (var j int) (minus (var j int) (var i int)))))))
(call (func putint int void) ((var i int)))))

Refeffing to the book, "Programming Language Pragmatics, Fourth Edition". Program should be able to generate pseudo-assembly code for the constructs used in Figure 15.2. Other statements (such as the for loop) or expressions (such as the division operator) used in Figure 15.10 on p. 804 are optional.
The pseudo-assembly code may either be returned as a list of strings or printed directly to the terminal (e.g., with println in Scheme).
You may omit the declaration block at the top of the code (the section beginning -- first few lines generated during symbol table traversal) in Figure 15.7. Begin with the label main:.

Explanation / Answer

In above question following pictures are missing

Figure 15.2. Figure 15.10 on p. 804 Figure 15.7.

Here is the functional language to traverse the following Abstract Syntax Tree:->

class Assign

{

double Subtree(ASTNode* ast)

   {

      if(ast->Type == NumberValue)

         return ast->Value;

      else if(ast->Type == UnaryMinus)

         return -Subtree(ast->Left);

      else

      {

         double v1 = Subtree(ast->Left);

         double v2 = Subtree(ast->Right);

         switch(ast->Type)

         {

         case OperatorPlus:  return v1 + v2;

         case OperatorMinus: return v1 - v2;

         case OperatorMul:   return v1 * v2;

         case OperatorDiv:   return v1 / v2;

         }

      }

}

In Pseudo code it would look like this

double Assign(subtree)

{

   if(subtree is numeric)

      return value;

   else

   {

      op = subtree.operator

      v1 = Assign(subtree.left)

      v2 = Assign(subtree.right)

      return v1 op v2;

   }

}