Skip to content

Operations on Stacks

Haoxi Zhan edited this page Nov 29, 2013 · 4 revisions

→ stack

The function which is used to push something into a stack is push-item. It is defined in line 56 of pushstate.clj.

(defn push-item
  "Returns a copy of the state with the value pushed on the named stack. This is a utility,
   not for use in Push programs."
  [value type state]
  (assoc state type (cons value (type state))))

stack →

Three functions are defined to get something from the stack. top-item returns the top item of a stack while stack-ref returns the item of a specific index in the stack. pop-item would pop the item and return a new stack without the top item.

Note
The pop-item is different from the pop in most languages, it doesn’t return the item but rather a new stack.

top-item

top-item is defined in line 62 of pushstate.clj.

(defn top-item
  "Returns the top item of the type stack in state. Returns :no-stack-item if called on
   an empty stack. This is a utility, not for use as an instruction in Push programs."
  [type state]
  (let [stack (type state)]
    (if (empty? stack)
      :no-stack-item
      (first stack))))
Note
top-item would only return the top item without changing the stack.

stack-ref

stack-ref is defined in line 71 of pushstate.clj.

(defn stack-ref
  "Returns the indicated item of the type stack in state. Returns :no-stack-item if called
   on an empty stack. This is a utility, not for use as an instruction in Push programs.
   NOT SAFE for invalid positions."
  [type position state]
  (let [stack (type state)]
    (if (empty? stack)
      :no-stack-item
      (nth stack position))))
NOTE: stack-ref would only return the indicated item without changing the stack.

pop-item

pop-item is defined in line 81 of pushstate.clj.

(defn pop-item
  "Returns a copy of the state with the specified stack popped. This is a utility,
   not for use as an instruction in Push programs."
  [type state]
  (assoc state type (rest (type state))))
NOTE: pop-item would only return a new state in which the item is popped in its stack. It would not return the item.

Special

end-environment

This function is defined in line 87 of pushstate.clj.

(defn end-environment
  "Ends the current environment by popping the :environment stack and replacing
   all stacks with those on the environment stack. Then, everything on the old
   :return stack is pushed onto the :exec stack."
  [state]
  (let [new-env (top-item :environment state)
        new-exec (concat (:exec state)
                         (:exec new-env))]
    (loop [old-return (:return state)
           new-state (assoc new-env
                            :exec new-exec
                            :auxiliary (:auxiliary state))]
      (if (empty? old-return)
        new-state
        (recur (rest old-return)
               (push-item (first old-return) :exec new-state))))))