DEV Community

ivan.gavlik
ivan.gavlik

Posted on

Practice working with Clojure vectors

Vector

A vector in Clojure is an ordered, indexed, immutable collection that allows efficient random access and fast additions at the end. They are immutable.

Vectors are defined using square brackets [] or by using the vector function:

;; Creating vectors
[1 2 3 4]          ;; Literal syntax
(vector 1 2 3 4)   ;; Using vector function
Enter fullscreen mode Exit fullscreen mode

Key Characteristics of Vectors:

  • Indexed (O(1) access time): You can retrieve elements using their index.

  • Ordered: Elements maintain the order in which they were inserted.

  • Immutable: Any modification creates a new vector instead of mutating the original.

  • Efficient addition/removal at the end: Adding elements to the end is fast (conj).

Usage & Operations:

Access Elements by Index

(def v [10 20 30 40])
(nth v 2)      ;; => 30
(get v 1)      ;; => 20
(v 3)          ;; => 40 (Vectors can be used as functions for indexing)
Enter fullscreen mode Exit fullscreen mode

Adding Elements

(conj [1 2 3] 4) ;; => [1 2 3 4] (adds to the end)
Enter fullscreen mode Exit fullscreen mode

Updating Elements

(assoc [1 2 3] 1 99) ;; => [1 99 3] (Replaces index 1 with 99)
Enter fullscreen mode Exit fullscreen mode

Removing Elements

Vectors do not have direct remove operations, but you can filter or use subvec:

(vec (remove #(= % 2) [1 2 3])) ;; => [1 3] (Removes 2)
(subvec [1 2 3 4] 1 3)          ;; => [2 3] (Slices vector from index 1 to 2)
Enter fullscreen mode Exit fullscreen mode

Iterating Over a Vector

(map inc [1 2 3]) ;; => (2 3 4)
(filter even? [1 2 3 4]) ;; => (2 4)
Enter fullscreen mode Exit fullscreen mode

Sorting a Vector

(sort [3 1 4 2])  ;; => (1 2 3 4)
(sort-by count ["apple" "kiwi" "banana"]) ;; => ("kiwi" "apple" "banana") (Sort by length)
Enter fullscreen mode Exit fullscreen mode

Task: Managing a Task List with Vector

Scenario:

You are building a simple task management system that stores tasks in a vector. Each task is represented as a map with the following keys:

  • :id (unique task identifier)
  • :title (task description)
  • :priority (one of :low, :medium, :high)
  • :completed? (boolean indicating if the task is done)

Goal:
Implement functions that allow you to manage tasks in the system:

  • Initialize Task List – Create a vector of sample tasks.

  • Add a Task – Insert a new task into the task list.

  • Remove a Task – Remove a task by its :id.

  • Mark a Task as Completed – Update a task’s :completed? status to true.

  • List All Pending Tasks – Return only tasks where :completed? is false.

  • Find Tasks by Priority – Retrieve all tasks with a specific priority (:low, :medium, or :high).

  • Sort Tasks by Priority – Sort the vector so :high priority tasks come first, followed by :medium, then :low.

  • Get Next Task – Return the highest-priority pending task that has not been completed.

Solution

;; Managing a Task

;; Initialize Task List
(defn init-task-list []
  (hash-map {})
  )

(defn valid-priority [priority]
  (or (= :low priority) (= :medium priority) (= :high priority))
  )


(defn create-task [id title desc priority]
  (when (valid-priority priority)
    {:id id :title title :description desc :priority priority :completed? false}
    )
  )

(defn task-not-exist? [task-list title]
  (= 0 (count (filter #(= (:title %)  title) task-list))
  ))

;; Add a Task
(defn add-task [task-list title desc priority]
  (when (task-not-exist? task-list title)
    (let [last-task-id (:id (last task-list) 0)
          next-task-id (inc last-task-id)
          task (create-task next-task-id title desc priority)]
      (conj task-list task)
      )
    )
  )

;; Remove a Task
(defn remove-task [task-list task-id]
  (remove #(= (:id %) task-id) task-list)
  )

;; Mark a Task as Completed
(defn mark-as-completed [task-list task-id]
  (let [task (first (filter #(= (% :id) task-id) task-list))
        index-of-task (index-of task-list task)]
    (when (not (nil? task))
      (assoc task-list index-of-task (assoc task :completed? true))
      )
    )
  )

;; List All Pending Tasks
(defn pending-tasks [task-list]
  (filter #(not (:completed? %)) task-list)
  )


;; Find Tasks by Priority
(defn filter-by-priority [task-list priority]
  (when (valid-priority priority)
    (filter #(= (:priority %) priority) task-list)
    )
  )

(defn priority-count [priority]
  (cond
    (= priority :high) 3
    (= priority :medium) 2
    (= priority :low) 1
    :else 0
    )
  )

(defn priority-higher-comparator [el1 el2] ()
  (let [priority1 (priority-count (el1 :priority))
        priority2 (priority-count (el2 :priority))]
    (compare priority2 priority1)
    )
  )

;; Sort Tasks by Priority
(defn sort-by-priority [task-list]
  (sort priority-higher-comparator task-list)
  )

;; Get Next Task
(defn next-task [task-list]
  (sort-by-priority (pending-tasks task-list))
  )
Enter fullscreen mode Exit fullscreen mode

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • --last-failed: Zero in on just the tests that failed in your previous run
  • --only-changed: Test only the spec files you've modified in git
  • --repeat-each: Run tests multiple times to catch flaky behavior before it reaches production
  • --forbid-only: Prevent accidental test.only commits from breaking your CI pipeline
  • --ui --headed --workers 1: Debug visually with browser windows and sequential test execution

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Practical examples included!

Watch Video 📹️

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay