Clojure Data Structures and Sequences
Clojure is a functional programming language built on the JVM that emphasizes immutability and persistent data structures. Its core collections and the concept of sequences form the backbone of how developers manipulate data in expressive and efficient ways.
🏛️ Core Data Structures
Lists
- Ordered, linked collections.
- Typically used for code representation and recursive processing.
(def my-list '(1 2 3 4))
(first my-list) ;; => 1
(rest my-list) ;; => (2 3 4)
Vectors
- Indexed, random-access collections.
- Efficient for lookups and appends.
(def my-vector [10 20 30])
(nth my-vector 1) ;; => 20
(conj my-vector 40) ;; => [10 20 30 40]
Maps
- Key-value pairs, similar to dictionaries.
- Support fast lookups and updates.
(def my-map {:a 1 :b 2})
(get my-map :a) ;; => 1
(assoc my-map :c 3) ;; => {:a 1 :b 2 :c 3}
Sets
- Collections of unique values.
- Useful for membership tests.
(def my-set #{1 2 3})
(contains? my-set 2) ;; => true
(disj my-set 1) ;; => #{2 3}
🔄 Sequences in Clojure
A sequence is not a collection type but an abstraction (the ISeq interface) that represents “one element followed by the rest.” This abstraction allows all collections—lists, vectors, maps, sets—to be treated uniformly.
Key Properties
- Lazy Evaluation: Sequences can be infinite, computed only when needed.
- Uniform Operations: Functions like
map,filter, andreducework across all collections. - Nil as Sentinel:
nilrepresents the end of a sequence.
Example: Sequence Functions
;; Map over a vector
(map inc [1 2 3]) ;; => (2 3 4)
;; Filter a list
(filter even? '(1 2 3 4 5)) ;; => (2 4)
;; Reduce a set
(reduce + #{1 2 3 4}) ;; => 10
Lazy Sequences
(def naturals (iterate inc 0))
(take 5 naturals) ;; => (0 1 2 3 4)
Here, iterate produces an infinite sequence, but take limits evaluation.
⚡ Why Sequences Matter
- They unify operations across different data structures.
- Enable functional pipelines for data transformation.
- Support lazy computation, making Clojure efficient for large or infinite datasets.
📖 Conclusion
Clojure’s immutable data structures and sequence abstraction provide a powerful foundation for functional programming. Lists, vectors, maps, and sets are seamlessly integrated with sequence operations, allowing developers to write concise, expressive, and efficient code.
No comments:
Post a Comment