Lex / Yacc用于布尔计算 [英] Lex/Yacc for Boolean Calculation

查看:350
本文介绍了Lex / Yacc用于布尔计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Lex / Yacc编写计算NAND布尔表达式的程序。

I'm trying to write a program for calculating a NAND boolean expression using Lex/Yacc.

例如,如果输入是true nand ),我的程序应该打印假

For example, if input is "true nand (false nand true)," my program should print "false"

这是我到目前为止,但我真的卡住了

This is what I have so far,, but I am really stuck

我错过了什么或做错了什么?

What am I missing or doing wrong?

%{
#include "y.tab.h"
%}


%%
"true"|"false" {return BOOL;}
"nand"         {return NAND;}
[()]           {return yytext[0];}

%%



boolean.y



boolean.y

%token BOOL NAND
%left NAND

%%
boolexp: boolexp NAND boolterm    {$$ = !($1 && $3);}
        | boolterm    {$$=$1;}
;

boolterm: '(' boolexp ')'
        | BOOL  {$$ = (strcmp($1, "true")) ? 1 : 0;} 
;

%%
#include <lex.yy.c>

int main(void) {
        yyparse();
}


推荐答案

更简单的时间,如果你使 TRUE FALSE 两个单独的令牌。

You'd have a lot easier time if you made TRUE and FALSE two separate tokens.

%token TRUE FALSE NAND
%left NAND

%%
boolexp: boolexp NAND boolterm    {$$ = !($1 && $3);}
        | boolterm    {$$=$1;}
;

boolterm: '(' boolexp ')' {$$ = $2;}
        | bool  {$$ = $1;}
;

bool: TRUE {$$ = 1;}
    | FALSE ($$ = 0;}
;

这篇关于Lex / Yacc用于布尔计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆