how do i implement a for loop in a math interpreter

how do I implement loops in a math interpreter?
it gets the tokens but discards them after reading them but I want to implement for loops and such, like > Σ(n=0;n+1,10) this wouldn't work currently as it would read it as Σ(0,1,10), are there any tutorials on this kind of stuff?
There are entire college courses on writing compilers and interpreters.

The problem is you have to accumulate tokens until they match a "production". A production evaluates a series of tokens "producing" a new token that represents the evaluated tokens.

Often compilers/interpreters are written using a lexical analyzer such as LEX.
A compiler/interpreter is often written using Bakcus-Naur form (BNF).
A program such as YACC
takes BNF and tokens produced by LEX and build a state machine that evaluates the desired grammar.

The BNF for your loop would look something like:
start_term:  identifier = integer
increment:   identifier + integer
end_term:    integer
sum_loop:    SIGMA ( start_term , increment , end_term )  

Last edited on
You have 3 expressions separated by a comma. Each expression is first converted into a sequence of tokens. This is an infix sequence. Some checking can be done on this - such as for the start term, the 2nd token is an '=' etc. This is then converted into a postfix sequence. Depending on how this is going to be executed, this postfix sequence could be stored so that the infix-postfix conversion is only done once. Then the postfix expression is evaluated as required.

As you are using variables, you need a symbol table which contains an entry for each variable used and it's current value.

I don't know what else your math interpreter is doing, but I'd expect it to be based around something like this. So your sum function is really just 3 expressions evaluated within a standard for loop for implementation.

How are you currently doing infix-postfix conversion?
you also need to be careful about such symbols. This is like how if you open c++ code in word and all the quotes become slant-quotes when it 'fixes' it for you, and then the slant quotes make the compiler blow up with crypic and dire messages of world ending proportions; I believe some of these symbols will appear over and over with different codes but similar or identical glyphs when printed. Depending on how the user is allowed to generate the symbols, this may be high risk.
i convert the expression using shunting-yard
You may find this useful.
Topic archived. No new replies allowed.