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.
function evaluateExpression(){
    var token = getToken();
    if( isNumber(token)){
        return token;
    }else if( isOpenParen(token)){
        return evaluateExpression();
    }
    var numOne = evaluateExpression();
    var nextToken = null;
    while( !isRightParen(nextToken)){
        nextToken = getToken();
        numOne = evaluate(token, numOne, nextToken);
    }
    return numOne;
}
The functions isNumber() and isLeftParen() do what they imply, return true if the token passed to it is a number or left parenthesis respectively.  The evaluate() function takes the operator token as well as the two numbers to evaluate them.  Eg, evaluate(+,2,4) would return 6 and evaluate(-,2,4) would return 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With