0 Replies - 1283 Views - Last Post: 12 January 2010 - 04:19 AM

#1 Raynes   User is offline

  • D.I.C Lover
  • member icon

Reputation: 615
  • View blog
  • Posts: 2,815
  • Joined: 05-January 09

[Lisp] An implementation of a simple stack in Clojure.

Posted 12 January 2010 - 04:19 AM

Description: To use this example, you'll need to build Clojure from the master branch on github, because this snippet uses features that aren't in Clojure 1.1, but will be in Clojure 1.2.This snippet defines a simple, but fully functional stack.
(deftype Stack [elements])

(def stack (Stack (ref ())))

(defn flip 
  "Flips a functions argument list."
  [f] (fn [& args] (apply f (reverse args))))

(defn push-stack
  "Pushes an item to the top of the stack."
  [x] (dosync (alter (:elements stack) (flip cons) x)))

(defn pop-stack
  "Pops an item from the top of the stack."
  [] (let [fst (first (deref (:elements stack)))] 
       (dosync (alter (:elements stack) rest)) fst))

(defn top-stack
  "Shows what's on the top of the stack."
  [] (first (deref (:elements stack))))

(defn empty-stack?
  "Tests whether or not the stack is empty."
  (= () (deref (:elements stack))))

Is This A Good Question/Topic? 0
  • +

Page 1 of 1