SE250:lab-8:hlin079

From Marks Wiki
Jump to navigation Jump to search

To get start with the lab I tried to compile the file and it gave me an error. I changed:

return sp >= str && stircmp( sp, end ) == 0
return sp >= str && stricmp( sp, end ) == 0

it can compile now .Then i construct an expression using mkNode that, when passed to

prefix tree, produces the output -(-(a b)).
ParseTree* t = mkNode( ’-’, mkNode( ’-’, mkNode( ’a’, 0 ), mkNode( ’b’, 0 ), 0 ),0).;

in order to make sure it is right i wrote a main function. i aslo got a graph for the tree. <sorry i can't upload it>

.After that i construct an expression that producesn ?(>(+(a b) c) *(z +(y b)) ?(=(a 2) -(x y) -(y x))).

ParseTree* t = mkNode( '?',mkNode( '>', mkNode('+',mkNode( 'a', 0 ), mkNode( 'b', 0 ),0),mkNode('c',0),0) ,mkNode('*',mkNode( 'z',mkNode( '+', mkNode( 'y', 0 ), mkNode( 'b', 0 ), 0 ),0),0),mkNode('?',mkNode( '=',mkNode( 'a',0), mkNode( '2', 0 ),0), mkNode( '-', mkNode('x',0 ),mkNode('y', 0 ),0), mkNode( '-', mkNode('y',0 ),mkNode('x', 0 ),0),0),0);

i toke me a while to figured out which 0 goes to which. .I have a graph for that tree but i can't upload it . .Question mark has three children. The second and third children are the thing goes to the left and right hand side of colon. .I write a (recursive) function to evaluate a parse tree that consists of nodes that are either digits or the operators +, -, * and /.

eval(ParseTree *node){
	  
	  if (node->name=='+'){
		  return eval(node->arg[0])+eval(node->arg[1]);
	  }
	  if (node->name=='-'){
		  return eval(node->arg[0])-eval(node->arg[1]);
	  }
	  if (node->name=='/'){
		  return eval(node->arg[0])/eval(node->arg[1]);
	  }
	   if (node->name=='*'){
		  return eval(node->arg[0])*eval(node->arg[1]);
	   }
	   if ((node->name>='0')||(node->name<='9')){
		   return node->name-'0';
	   }
  }

Hlin079 .