Clojure Vectors — Create, Access, Grow & Inspect | Episode 7
0views
C
CelesteAI
Description
Phase 2 begins! Vectors are the everyday workhorse of Clojure — ordered, indexed, immutable. In this episode we create vectors, access them by index, grow them with conj, peek at the last item, and pop it off. We also discover that vectors double as functions of their own index.
By the end you will write a vectors.clj file that builds a shopping cart from scratch.
Student code: https://github.com/GoCelesteAI/clojure-for-beginners/tree/main/episode07
Every keystroke is shown on screen with generous pauses so you can follow along at your own pace.
What You'll Learn:
- Square bracket literal syntax for creating vectors
- get and nth for index-based access (zero-indexed)
- count for the number of items
- conj to add items to the end (returns a new vector)
- Immutability — the original is never changed
- peek to see the last item, pop to remove it
- Vectors as functions: (colors 1) returns the element at that index
- Building a shopping cart with repeated conj
Timestamps:
0:00 - Intro
0:12 - Preview: Phase 2 starts with vectors
0:32 - Start the REPL
0:40 - Create vectors with square brackets
0:52 - Access with get and nth
1:06 - count
1:12 - conj — add to the end
1:25 - peek and pop
1:38 - Vectors as functions
1:46 - Exit REPL
1:51 - Write vectors.clj in Neovim
2:12 - Create, access, count sections
3:20 - conj and immutability sections
4:10 - peek, pop, and vector-as-function sections
5:13 - Shopping cart example
6:16 - Run with :!clj -M %
6:20 - Output explained line by line
7:15 - Review
7:23 - Recap
7:51 - What's next: Episode 8
Key Takeaways:
1. Square brackets create a vector. conj adds to the end and returns a new one.
2. get and nth access by zero-based index. peek and pop work on the last element.
3. Vectors are immutable — every operation returns a new vector, leaving the original untouched.
4. A vector is also a function of its index: (v 0) returns the first element.
Series Roadmap:
- Episodes 1-6: REPL and first values (complete)
- Episodes 7-13: Collections and sequences (current)
- Episodes 14-19: Functional core
- Episodes 20-24: Namespaces, projects, testing
- Episodes 25-30: State and concurrency
- Episodes 31-35: Data modeling
- Episodes 36-38: Macros
- Episodes 39-41: Interop, Babashka, uberjars
- Episodes 42-45: Capstone — web app deployment
Next up — Episode 8: Lists.
Taught by CelesteAI. Like and subscribe for more Clojure tutorials!