Search code examples
schemepostfix-notation

program using Scheme that evaluates a postfix expression


I want to convert a postfix expression using scheme The expression will be given to the interpreter as a list of operands and operators such as display( postfix(30 8 7 + / 3 4 - *) ) This example should return -2 as answer.


Solution

  • Here's pseudo-code:

    • Initialize stack to empty list
    • For each element e in the expression:
      • if e is a number, push it onto the stack
      • otherwise, call the function corresponding to the operator (you can use an association list or cond to find this), passing the stack as the parameter
        - The function pops the needed arguments off the stack
        - It calculates the result
        - It pushes the result onto the stack
        - It returns the updated stack, which the main loop assigns back to the stack variable
    • At the end, print the top element of the stack