1

I am writing a small interpreter to show an example of Backus-Naur form and i would like to ask for help representing some data.

<statement> : <assignment> | HALT | PRINT(<variable>)
<assignment> : <variable> = <expression>
<expression> : <term> | <term><operator><expression>
<term> : <number> | <variable>
<variable> : x | y | z
<operator> : + | -
<number> : 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

As you can see everything is encapsulated in a statement. An then there assignments and expression. An expression encapsulates a term, which encapsulate a number and a variable. An assignment encapsulates a variable and a expression. My question is what data structure do i use to represent all of this? I am thinking it should be a set, but then that raises the question should i have nested sets?

4

2 回答 2

1

这看起来像一个简单的表达式解析器,添加了一些命令(PRINT 和 HALT)。解析此类事物的最简单方法可能是使用递归下降解析器。如果您正在构建解释器,那么您可以在解析时解释表达式,或者构建表达式的后缀(或前缀)表示以供以后解释。

于 2010-09-17T02:40:56.640 回答
0

我会使用面向对象的方法:

public class State { /* ... */ }
public abstract class Statement {
  // ...
  public abstract void evaluate(State state);
  // ...
}

public class AssignmentStatement extends Statement {
  // ...
  private Variable var;
  private Expression expr;
  // ...
}

public class HaltStatement extends Statement { /* ... */}

public class PrintStatement extends Statement {
  private Variable var;
}

等等。根据您需要与变量关联的信息量(可能是它们的声明位置、此事件出现在哪一行和哪一列等),您可以不使用Strings 作为变量类型,使用 sint作为数字类型。

于 2010-09-17T02:08:28.487 回答