liveBook · Manning

Pop

As explained in Clojure: The Essential Reference

pop is a Clojure function that returns a collection with its end element removed according to the collection's pop semantics.

pop returns a collection with its head element removed, but “head” depends on the collection. For vectors, it removes the last element; for lists and queues, it removes the first-added element. It returns nil when given nil. section 12.6

Use pop with collections implementing IPersistentStack, especially vectors, lists, and queues.

  • A vector behaves like a LIFO stack: (pop ["a" "b" "c"]) returns ["a" "b"]. section 12.6
  • A queue removes its first-added element, while an empty queue may be popped; empty vectors and lists throw IllegalStateException. section 12.6
  • Passing a collection without IPersistentStack support can produce ClassCastException; use butlast for sequence-oriented last-element removal, though it is linear. section 12.6 section 10.1

Checking balanced delimiters with a vector stack

A vector, conj, peek, and pop can implement a LIFO stack while scanning a Clojure form. Matching delimiters pop the opening bracket; mismatches throw an exception. A balanced form leaves [].

Processing a vector from the end

A loop can repeatedly inspect the final element with peek, remove it with pop, and accumulate transformed results. (reverse-mapv str (vec (range 10))) returns ["9" "8" "7" "6" "5" "4" "3" "2" "1" "0"].

How Clojure: The Essential Reference covers it

How deep it goes
Defines the contract, supported interfaces, collection-specific semantics, exceptions, nil behavior, and performance contrast with butlast.
Examples
Demonstrates vector, list, and queue removal, delimiter checking, and reverse traversal with peek and pop.
What it assumes
Assumes familiarity with Clojure collections and functions while clarifying collection ordering, persistent stacks, and empty-input behavior.
What you can do after
Apply pop to supported persistent collections while selecting behavior appropriate to stacks, queues, vectors, and sequence processing.
How it connects
Connects pop with peek, vectors, lists, queues, stacks, conj, and butlast.

Also explained in

Compare how 4 books explain pop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.