ITeye博客

虎书P8问题(1)

pf_miles · 2008-08-16 20:04 · Programming · C · C++ · C# · Markdown

见《虎书》中文版第8页; 我的答案:


#ifndef P8Q1_H
#define P8Q1_H
#include "slp.h"

int resolveStm(A_stm stm);
int resolveExp(A_exp exp);
int resolveExpList(A_expList expList);
int countExpInExpList(A_expList expList);

#endif


#include "p8q1.h"

int resolveStm(A_stm stm){
    int temp1 = 0, temp2 = 0;
    if(stm->kind == A_compoundStm){
	temp1 = resolveStm(stm->u.compound.stm1);
	temp2 = resolveStm(stm->u.compound.stm2);
	return temp1>temp2? temp1:temp2;
    }else if(stm->kind == A_assignStm){
	return resolveExp(stm->u.assign.exp);
    }else if(stm->kind == A_printStm){// the way out
    	return countExpInExpList(stm->u.print.exps);
    }else{
	return 0;
    }
}

int countExpInExpList(A_expList expList){
    if(expList->kind == A_lastExpList){
	return 1;
    }else if(expList->kind == A_pairExpList){
	return 1 + countExpInExpList(expList->u.pair.tail);
    }else{
	return 0;
    }
}

int resolveExpList(A_expList expList){
    int temp1,temp2;
    if(expList->kind == A_pairExpList){
	temp1 = resolveExp(expList->u.pair.head);
	temp2 = resolveExpList(expList->u.pair.tail);
	return temp1>temp2?temp1:temp2;
    }else if(expList->kind == A_lastExpList){
	return resolveExp(expList->u.last);
    }else{
	return 0;
    }
}

int resolveExp(A_exp exp){
    int temp1,temp2;
    if(exp->kind == A_idExp){
	return 0;
    }else if(exp->kind == A_numExp){
	return 0;
    }else if(exp->kind == A_opExp){
	temp1 = resolveExp(exp->u.op.left);
	temp2 = resolveExp(exp->u.op.right);
	return temp1>temp2?temp1:temp2;
    }else if(exp->kind == A_eseqExp){
	temp1 = resolveStm(exp->u.eseq.stm);
	temp2 = resolveExp(exp->u.eseq.exp);
	return temp1>temp2?temp1:temp2;
    }else{
	return 0;
    }
}


main.c:


#include <stdio.h>
#include "util.h"
#include "prog1.h"
#include "slp.h"
#include "p8q1.h"

main(){
    printf("%d\n",resolveStm(prog()));
}


输出结果:2

体会:对于“目标”需要特殊处理,“目标”就是解析程序的出口。

评论(1)

  1. #1 楼 · pf_miles · 2008-08-16 23:48

    上面的代码有缺憾,没有考虑“如果print语句中的expList里面还有print语句”这种情况,需要更改countExpInExpList方法,它也需要和另两个方法互相递归,要解析print语句中的print语句。

    
    int countExpInExpList(A_expList expList){
        int temp1,temp2;
        if(expList->kind == A_lastExpList){
            temp1 = resolveExp(expList->u.last);
            return temp1>1?temp1:1;
        }else if(expList->kind == A_pairExpList){
            temp1 = 1 + countExpInExpList(expList->u.pair.tail);
            temp2 = resolveExpList(expList->u.pair.tail);
            return temp1>temp2?temp1:temp2;
        }else{
            return 0;
        }
    }
    
    
    

评论功能维护中,当前仅展示历史评论。