Stack: Difference between revisions

988 bytes added ,  14 years ago
Line 375:
"Tests whether or not the stack is empty."
[] (= () (deref (:elements stack))))</lang>
 
We can make this a bit smaller and general by using defprotocol along with deftype. Here is a revised version using defprotocol. Note that in both of these examples, the flip function is unnecessary. You could accomplish the same thing using a lambda, but flip is much more general.
 
<lang lisp>(defn flip
"Flips a functions argument list."
[f] (fn [& args] (apply f (reverse args))))
(defprotocol StackOps
(push-stack [this x] "Pushes an item to the top of the stack.")
(pop-stack [this] "Pops an item from the top of the stack.")
(top-stack [this] "Shows what's on the top of the stack.")
(empty-stack? [this] "Tests whether or not the stack is empty."))
(deftype Stack [elements]
StackOps
(push-stack [x] (dosync (alter elements (flip cons) x)))
(pop-stack [] (let [fst (first (deref elements))]
(dosync (alter elements rest)) fst))
(top-stack [] (first (deref elements)))
(empty-stack? [] (= () (deref elements))))
(def stack (Stack (ref ())))</lang>
 
== {{header|Common Lisp}} ==
72

edits