CS241: Spring 2015 -- Expressions

  1. My proto life code
  2. One atom thick! Moore's law
  3. random walk
  4. Two new data structures: stack and queue
  5. Expression evaluation
    1. Introduction to expressions: prefix, infix, and postfix
    2. Evaluating arbitrary infix expressions; not so easy!!
    3. postfix evaluation
      while (more input) {
         next = nextToken()
         if (next is operand)
            push(next)
         else apply next to top two operands and push the result
      }
      answer is on top of the stack
      
    4. Designing a Stack
      1. Methods
        1. void push(Foo) - adds the Foo to the tail of the list
        2. Foo pop() - removes and returns the Foo at the tail
        3. boolean isEmpty() - true if is empty!
        4. Foo top() - returns the Foo at the tail without deleting it
      2. Representation
        1. array
        2. ArrayList
      3. What will be stored in the Stack (i.e. what is Foo above)?
        1. String?
        2. Object?
        3. Operand?
        4. Stackable?
    5. converting infix to postfix expressions (without parentheses!):
      while (more input) {
         next = nextToken()
         if (next is operand) 
            emit next
         else {
            while (!stack.isEmpty() && (precedence(top()) >= precedence(next))) {  
               emit(pop());
            } // while
            push(next)
         } // else
      }
      
      while !stack.isEmpty()
         emit(pop())
      
    6. parentheses!
      1. Insight: parentheses promote the precedence of everything inside them above everything -- thus, must emit all intraparenthetic operators before any following operators
      2. Treat ('s as operators, except you never emit them, with the following changes
      3. "(" as the lowest precedence than any other operator (so any operator may be pushed on top of it)
      4. ")" never goes on the stack, so if you also give it the lowest precedence of anything, the while loop (in the pseudocode above) will pop and emit everything on the stack! You must modify that loop to stop when a "(" is popped (then discard it and the close paren)