next up previous
Next: 2.6.2 Using the J Up: 2.6 Data Abstraction Previous: 2.6 Data Abstraction

2.6.1 J Data Abstraction for Stacks

We define the stack data type to be a collection of J items together with the following operations:

make_stack ==> constructs a stack
stackp obj ==> 1 if obj is a stack, else 0
empty_stackp stack ==> 1 if stack empty, else 0
push_stack item ; stack ==> put item on stack
pop_stack stack ==> remove last item pushed on stack
top_stack stack ==> return last item pushed on stack
                      without removing that value from stack
We represent a stack as a J boxed list which has a stack "tag" of 'stack' as its first item. First we define the helping words:
box =: <
open =: >
match =: -:
first =: {.
append =: ,
drop_last =: _1 & }.
last =: _1 & {

stack_tag =: box 'stack'
the_empty_stack =: box stack_tag
The stack operations may be written as:
make_stack =: monad define 'the_empty_stack'
stackp =: monad define 'stack_tag match first open y.'
empty_stackp =: monad define 'the_empty_stack match y.'

push_stack =: monad define script
('item' ; 'obj') =. y.
if. not stackp box obj
  do. error 'wrong type second input to push_stack' ; obj
  else. box obj append box item
end.
)

pop_stack =: monad define script
if. not stackp y.
  do. error 'wrong type input to pop_stack' ; y.
  else. box drop_last open y.
end.
)

top_stack =: monad define script
if. not stackp y.
  do. error 'wrong type input to top_stack' ; y.
  else. open last open y.
end.
)

next up previous
Next: 2.6.2 Using the J Up: 2.6 Data Abstraction Previous: 2.6 Data Abstraction
2002-09-27