Clojure Koans 4 Vectors Notebook

Hi there!

If you're new to my Clojure Koan notebooks, be aware: This entire notebook is one big spoiler which contains my answers for the Clojure Koans.

Let's get right into it!

{:deps {org.clojure/clojure {:mvn/version "1.10.1"}
        ;; complient is used for autocompletion
        ;; add your libs here (and restart the runtime to pick up changes)
        compliment/compliment {:mvn/version "0.3.9"}}}
deps.edn
Extensible Data Notation
{:hello (clojure-version)}
0.1s
Clojure

;; "You can use vectors in clojure as array-like structures"
(= 1 (count [42]))
;; skill 4001: Get the size/length of a Clojure vector with the `count` function
0.1s
Clojure
;; "You can create a vector from a list"
(= [1] (vec '(1)))
;; skill 4002: Convert a list into a vector using the `vec` function
0.0s
Clojure
;; "Or from some elements"
(= [nil nil] (vector nil nil))
;; skill  4003: Create a vector from some number of items using the `vector` function
0.0s
Clojure
;; "But you can populate it with any number of elements at once"
(= [1 2] (vec '(1 2)))
0.0s
Clojure
;; "Conjoining to a vector is different than to a list"
(= [111 222 333] (conj [111 222] 333))
;; skill 4004: Append to the end of a vector by using `conj`
;; skill 4005: Prepend to (insert at) the beginning of a list by using `conj`
0.0s
Clojure
;; "You can get the first element of a vector like so"
(= :peanut (first [:peanut :butter :and :jelly]))
;; skill 4006: Get the 0th element of a vector using the `first` function
0.0s
Clojure
;; "And the last in a similar fashion"
(= :jelly (last [:peanut :butter :and :jelly]))
;; skill 4007: Get the final element of a vector using the `last` function
0.0s
Clojure
;; "Or any index if you wish"
(= :jelly (nth [:peanut :butter :and :jelly] 3))
;; skill 4008: Get an element of a vector at any index using the `nth` function
0.0s
Clojure
;; "You can also slice a vector"
(= [:butter :and] (subvec [:peanut :butter :and :jelly] 1 3))
;; skill 4009: Splice a vector using the `subvec` function
0.0s
Clojure
;; "Equality with collections is in terms of values"
(= (list 1 2 3) (vector 1 2 3))
;; skill 4010: Compare a vector and list with the same value contents to return true.
Clojure

Closing notes: Vectors and lists seem quite similar on the surface, but under the hood, they have quite a few differences. I will be updating both the notebook on lists as well as this one in the coming few days to further delve into what I have learned, such as:

  • Which is a sequence, a list, a vector, both, or neither?

  • What defines a Clojure sequence exactly?

  • What are some more ways to explore & test Clojure?

Runtimes (1)