求幂运算的明确语法 [英] Unambiguous grammar for exponentiation operation

查看:84
本文介绍了求幂运算的明确语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  E-> E + T | E-T | T 
T-> T * F | T / F | F
F->我(E)

我如何修改此语法以允许求幂运算 ^ ,这样我就可以写 i + i ^ i * i 吗?因为我们知道 ^ 的操作顺序更高,所以我所知道的是我必须使其正确关联。

解决方案

在EBNF中(扩展了Backus-Naur表格),则可能如下所示:

  expr->字词[(’+’|’-’)字词] * 
字词->因子[('*'|‘/’)因子] *
因子->基本[’指数] *
基本-> ‘(’expr’)’|标识符|数字
指数-> ‘(’expr’)’|标识符|数字

(取自此处



翻译为您的符号(数字和数字之间没有区别

  E-> E + T | E-T | T 
T-> T * F | T / F | F
F-> F ^ X | B
B->我(E)
X->我(E)

为了清楚起见,可以合并 B和 X。 p>

E -> E+T | E-T | T
T -> T*F | T/F | F
F -> i | (E)

How can I modify this grammar to allow an exponentiation operation ^ so that I can write i+i^i*i? Since we know that order of operations is higher for ^ then all I know is that I must make it right associative.

解决方案

In EBNF (Extended Backus-Naur Form), this could look as follows:

expr -> term [ ('+' | '-') term ]*
term -> factor [ ('*' | '/') factor ]*
factor -> base [ '^' exponent ]*
base -> '(' expr ')' | identifier | number
exponent -> '(' expr ')' | identifier | number

(taken from here)

Translated to your notation (no distinction between numbers and identifiers):

E -> E+T | E-T | T
T -> T*F | T/F | F
F -> F^X | B
B -> i | (E)
X -> i | (E)

One could merge "B" and "X" for the sake of clarity.

这篇关于求幂运算的明确语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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