Being fairly new to clojure ecosystem. I thought it would be better to be dedicating a post to each of the data structures in Clojure.

Clojure has the following data structures

  ;; Lists
  ;; Vectors
  ;; Hashmaps
  ;; Sets

These are concrete data types, which are implementation of abstract data types.

This post will try to scratch the surface of - LISTS

LISTS


As the name goes, are a collection of group of values.

  '(1 2 3)
  ; => (1 2 3)

  (type ( `(1 2 3))
  ; => clojure.lang.PersistentList

Funny thing, by mistake I typed this in the repl.

  `(1 2 3)
  ; => (1 2 3)

  ; or another way to represent lists
  ; I prefer the previous

  (list (1 2 3))
  ; => (1 2 3)

  (type `(1 2 3))
  ; => clojure.lang.Cons

Turns out ` is for denoting ‘Cons’ which is another list-like structure in LISP. The term ‘cons’ is derived from “constructing a pair”, where these pairs could then be chained together to build a list. Will dig in deep for more about it

Operations on LISTS


Lists are comparable

  (= '(1 2 3) '(1 2 3))
  ; => true

We can modify lists by conjoing on it, this operation adds the element to the front of the list Because lists function as a singly linked list in clojure, insertion of an element occurs at the front of the list.

  '(1 2 3)
  ; => (1 2 3)

  (type ( `(1 2 3))
  ; => clojure.lang.PersistentList
  (conj '(1 2 3) 4)
  ; => (4 1 2 3)
  ;; first element of the list
  (first '(1 2 3))
  ; => 1

  ;; second element of the list
  (second '(1 2 3))
  ; => 2

  ;; last element of the list
  (last '(1 2 3))
  ; => 3

  ;; nth get the element from the given index beginning with 0
  (nth '(1 2 3) 2)
  ; => 3

Lists are suitable for small collections and can be slow in getting elements. For faster access to every element we would look at VECTORS (or Arrays as we know) in the next post.