-5

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.

  • 1
    StackOverflow is not a homework service. SO expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592). Please update your question to show what you have already tried in a [mcve]. For further information, please see [ask], and take the [tour] :) – Barmar Nov 07 '18 at 16:24
  • Its not for homework i tried solving it multiple time sir, i just need some help. – darth_sidious Nov 07 '18 at 16:26
  • 1
    If you tried solving it multiple times, show what you tried. Then we can point out where you went wrong and how to fix it. But we're not going to write it for you. – Barmar Nov 07 '18 at 16:29
  • i'm sorry sir it is but i tried a lot,i dont want a bad grade either can you please help me. – darth_sidious Nov 07 '18 at 16:29
  • You need to implement a stack for the operands. Loop over the list. When you get a value, push it onto the stack. When you get an operator, pop the operands off the stack, call the corresponding function, and push the result onto the stack. – Barmar Nov 07 '18 at 16:30
  • Bad grade? I thought it wasn't homework. – Barmar Nov 07 '18 at 16:30
  • Thanku sir, i wish someone provided me a pseudo code or something i'm new to programming i want to be like u someday. – darth_sidious Nov 07 '18 at 16:31
  • At the end, display the top element of the stack. – Barmar Nov 07 '18 at 16:31

1 Answers1

1

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
Barmar
  • 741,623
  • 53
  • 500
  • 612