I’m making a simple program in C an Lisp arithmetic calculator just involving integers and "+ - * /" operators, I’m doing this for learning purposes it’s not my homework or something like that.
So I have made a function which will correctly parse something like this (+ 2 3) it would output 5, so I know how to handle non nested statements but what when I have something like this (+ (* 2 3) (- 4 2)) so it seems like I can use recursion to solve this, but I don’t know really how to do it.
My logic is following(in pseudo code):`
function parse_line(int n)
get_input(string);
if string[n] == '('
if string[n+1] == operator
if string[n+3] == number
result = parseAllNumbers(); //between ( )
return result;
if string[n+3] == '('
parse_line(n+2);
`
So is my logic correct here, if I have (+ (* 2 3) (- 4 2)) I would just calc. (* 2 3), how would I go about calculating the (- 4 2) and then adding those two result together
You’re definitely on the right track.
Assume that we have a
getToken()function written which reads the next logical token in the string from the current position. A logical token would be a number, ‘(‘, ‘)’ or any of the four operators. Then we can recursively evaluate expressions.The functions
isNumber()andisLeftParen()do what they imply, return true if the token passed to it is a number or left parenthesis respectively. Theevaluate()function takes the operator token as well as the two numbers to evaluate them. Eg,evaluate(+,2,4)would return6andevaluate(-,2,4)would return2.