Pop

From REALbasicWiki

Jump to: navigation, search

Pop is a array function. It removes the last element of an array and returns it to the caller. Calling Pop on an empty array results in an OutOfBoundsException.

[edit] Syntax

Function Pop() as Type


[edit] A Quick Introduction to Stacks

A [stack] is a container defined by two operations, Push and Pop. Push adds an element to the stack, and Pop remove the last element added and returns it. This is the source of the idea and name of the REALbasic function. You can use a REALbasic array as a stack with Append supplying the push operation.

The classic example of a stack in action is an RPN expression evaluator. Here is a quick implementation demonstrating a REALbasic array in use as a stack. Here, an RPN expression is represented as a Variant array with elements of type Integer being operands and elements of type String being operators.

Function RPNEvaluate(expression() as Variant) As Integer
  dim operands() as Integer

  for i as Integer = 0 to UBound(expression)
    if expression(i).Type = Variant.TypeInteger then
      operands.Append expression(i).IntegerValue
    else
      dim y as Integer = operands.Pop
      dim x as Integer = operands.Pop
      
      select case expression(i).StringValue
      case "+"
        operands.Append x + y
        
      case "-"
        operands.Append x - y
        
      case "*"
        operands.Append x*y
        
      else
        //bad expression
      end select
    end if
  next
  
  //UBound(operands) should be 0
  return operands.Pop
End Function


And here is a test case.

dim theAnswer as Integer = RPNEvaluate(Array(1, 2, "+", 4, "*", 3, "+"))
theAnswer.ShouldBe 15
Personal tools
related