Sunday, May 11, 2014

Clojure Koans Answers and Explanations - 3 - Vectors

After the koans on equality and lists, here are the solutions on vectors.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;1
(= __ (count [42]))
; if you are coming from Jave, treat this like
; the size() method
; again, the answer matches with exercise number
; conspiracy
(= 1 (count [42]))
; 42
; again?
; look at this

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;2
(= __ (vec nil))
; if nil is nothing, what else would bring this concept home
; then []
; vec is used to create vector from another collection
(= [] (vec nil))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;3
(= __ (vec '(1)))
; populates the vector with 1
(= [1] (vec '(1)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;4
(= __ (vector nil))
; this instructs Clojure to create a new vector
; and put inside that vector
; whatever follows
(= [nil] (vector nil))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;5
(= [1 __] (vec '(1 2)))
; as noted above vec is used to bulk transfer elements
(= [1 2] (vec '(1 2)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;6
(= __ (conj (vec nil) 333))
; remember conj adds to the end of vector
; which is the sane thing to do if you consider
; the asymptotic complexities
(= [ 333] (conj (vec nil) 333)) ; and not
; (= [nil 333] (conj (vec nil) 333))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;7
(= __ (first [:peanut :butter :and :jelly]))
; no surprises
(= :peanut (first [:peanut :butter :and :jelly]))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;8
(= __ (last [:peanut :butter :and :jelly]))
; if you weren't surprised earlier, you wont be now either
(= :jelly (last [:peanut :butter :and :jelly]))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;9
(= __ (nth [:peanut :butter :and :jelly] 3))
; nth is an oft-used funtion
; syntax is (nth of n)
; of indicates a collection and n an index
(= :jelly (nth [:peanut :butter :and :jelly] 3))
; yeah nth starts counting from 0

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;10
(= __ (subvec [:peanut :butter :and :jelly] 1 3))
; start is inclusive and end is not
; counting starts at 0
(= [:butter :and] (subvec [:peanut :butter :and :jelly] 1 3))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;11
(= (list 1 2 3) (vector 1 2 __)))
; this one takes the cake
; if you are coming from a procedural languages
; this one is hard to digest
; Remember Clojure compares values
(= (list 1 2 3) (vector 1 2 3))



No comments:

Post a Comment