ColdFusion in Context: Stack

Suppose you wanted to implement an algorithm that uses a stack. For example, one approach to a depth-first walk through a tree uses a stack. This tip shows one way that ColdFusion easily supports stack manipulation.

The major stack operations are "push" to add something to the stack (as when a food handler adds plates to a spring-loaded plate holder at a cafeteria), read (to examine the topmost item), and "pop" to remove the item most recently added. It turns out that ColdFusion has functions that readily use lists as stacks.

Stack 'Em

To show how this works, you'll need manipulation logic and an entry form. Call this code stack.cfm. If the user has activated the form, then the value returned by its submit buttons (both named "doit") will be defined. For ease of use, the form variable "stack" is converted to a local variable "myStack", then back again so the form can carry its modified value to the next use of the form.

Three ColdFusion functions seem to be made for working with stacks. If an item needs to be removed from the stack, the ListRest function does quite nicely. Ignoring the first value, it returns the rest of the list. If an item needs to be added, the ListPrepend function pushes a value onto the begining of the list. If the top-most item is required, the ListFirst function does this nicely. Each of these functions has similar syntax. The first parameter is the list name; the last parameter, the list of delimiters, can be omitted if a bare comma (no space) is used as the delimiter. For clarity, a delimiter other than a comma is used for this demonstration.

After manipulation, the form itself is displayed, preceded by the value of the top-most item (if applicable) and the value of the stack itself.

<cfif isDefined("form.doit")>
  <cfset myStack=form.stack>
  <cfif form.doit is "Pop">
    <cfif ListLen(myStack,";")>
      <cfset myStack=ListRest(myStack,";")>
    <cfelse>
      The stack is already empty.
    </cfif>
  <cfelse>
    <cfif len(form.Item)>
      <cfset myStack=ListPrepend(myStack,form.Item,";")>
    <cfelse>
      Enter an item prior to pressing "Push".  No action was taken.
    </cfif>
  </cfif>
<cfelse>
  <cfset myStack="">
</cfif>

<cfif ListLen(myStack,";")>
  The top-most item is <cfoutput>#ListFirst(myStack,";")#</cfoutput><br>
</cfif>
The stack is [<cfoutput>#myStack#</cfoutput>].<br>
<form name="modstack" action="stack.cfm" method="post">
Remove an item...<input type="submit" name="doit" value="Pop"><br>
or Push this item: <input type="text" name="item" value="">
<input type="submit" name="doit" value="Push">
<input type="hidden" name="stack" value=<cfoutput>"#myStack#"</cfoutput>>
</form>

Watch 'Em

Browse stack.cfm. Push items onto the stack; remove items from the stack. Then consider how you will use stacks to support your applications. =Marty=