ClojureDocs

Nav

Namespaces

pop

clojure.core

Available since 1.0 (source)
  • (pop coll)
For a list or queue, returns a new list/queue without the first
item, for a vector, returns a new vector without the last item. If
the collection is empty, throws an exception.  Note - not the same
as next/butlast.
4 Examples
user=> (peek [1 2 3])
3
user=> (pop [1 2 3])
[1 2]
user=> (peek '(1 2 3))
1
user=> (pop '(1 2 3))
(2 3)
user=> (peek ())
nil
user=> (pop ())
IllegalStateException Can't pop empty list

user=> (peek [])
nil
user=> (pop [])
IllegalStateException Can't pop empty vector

user=> (peek (clojure.lang.PersistentQueue/EMPTY))
nil
user=> (into [] (pop (clojure.lang.PersistentQueue/EMPTY)))
[] ;; Can pop empty Queue
;; Use a vector as a LIFO stack to check for balanced brackets

(require '[clojure.set :refer [map-invert]])

(defn balance [form]
  (let [brackets {\[ \] \( \) \{ \}}
        scan (fn [q x]
               (cond
                 (brackets x) (conj q x)
                 ((map-invert brackets) x)
                 (if (= (brackets (peek q)) x)
                   (pop q)
                   (throw
                     (ex-info
                       (str "Unmatched delimiter " x) {})))
                 :else q))]
    (reduce scan [] form)))

(balance "(let [a (inc 1]) (+ a 2))")
;; ExceptionInfo Unmatched delimiter ]

(balance "(let [a (inc 1)] (+ a 2))")
;; []
;;basic example on vector and list

;;pop on vector returns a new vector removing the last element
(pop [1 2 3])
;; [1 2]

;;pop on list returns a new list removing the first element
(pop '(1 2 3)) ;; (2 3)
See Also

For a list or queue, same as first, for a vector, same as, but much more efficient than, last. If ...

Added by jjcomer

Returns a possibly empty seq of the items after the first. Calls seq on its argument.

Added by Yun

conj[oin]. Returns a new collection with the xs 'added'. (conj nil item) returns (item). (co...

Added by ryo

Return a seq of all but the last item in coll, in linear time

Added by bfontaine

Removes the last item from a transient vector. If the collection is empty, throws an exception. Re...

Added by mars0i
1 Note
    By , created 12.5 years ago, updated 12.5 years ago

    Small reminder:


    Do not work for arbitrary seq but just for persistent types implementing clojure.lang.IPersistentStack (like clojure.lang.Persistent*).


    Example:

    user> (pop (cons 1 '()))
    ; Evaluation aborted.
    
    do not work because type is clojure.lang.Cons but

    user> (pop (conj '() 1))
    ()
    
    works because type is clojure.lang.PersistentList.