Saturday, May 10, 2014

Clojure Koans Answers and Explanations - 2 - Lists

After the Clojure Koan on equalities, here is the one on lists.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;1
(= '(__ __ __ __ __) (list 1 2 3 4 5))
; a list can be expressed as quoted form
; these would be different from
; (1 2 3 4 5)
; If you are coming from a statically typed language try these
(type ( list 1 2 3 4 5))
(type '(1 2 3 4 5))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;2
(= __ (first '(1 2 3 4 5)))
; first does what you would expect it to do
; unless you are out of your senses
; for those coming from Lisp it is what you have been calling
; car
>(car (list 1 2 3 4 5))
; yields 1
; so the answer here is
(= 1 (first '(1 2 3 4 5)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;3
(= __ (rest '(1 2 3 4 5)))
; a mirror image of first
; Lispers call this cdr
>(cdr (list 1 2 3 4))
;(2 3 4)
(= (list 2 3 4 5) (rest '(1 2 3 4 5)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;4
(= __ (rest '(100)))
; where as cdr would return nil
; rest returns an empty list
(= (list) (rest '(100)))
; somehow we miss that nil, it appears to be the right thing :-)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;5
(= __ (cons :a '(:b :c :d :e)))
; cons would add to the beginning
(= '(:a :b :c :d :e) (cons :a '(:b :c :d :e)))
; both Lisp and Clojure allow you to pad nil
(cons nil (list 1)) ; yields (nil 1)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;6
(= __ (conj '(:a :b :c :d :e) 0))
; adds 0
(= '(0 :a :b :c :d :e) (conj '(:a :b :c :d :e) 0))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;7
(= __ (peek '(:a :b :c :d :e)))
; using it like stack to 'see' the first value
; remember for a list returns first value
; for a vector it returns last.
(= :a  (peek '(:a :b :c :d :e)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;8
(= __ (pop '(:a :b :c :d :e)))
; a Clojure trap for some
; for a list works like rest
; except for one major difference noted below
; for vector yields the last value
(= '(:b :c :d :e) (pop '(:a :b :c :d :e)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;9
(= __ (try
          (pop '())
          (catch IllegalStateException e "No dice!")))
; popping an empty list yields the exception
; IllegalStateException Can't pop empty list
(= "No dice!" (try
          (pop '())
          (catch IllegalStateException e "No dice!")))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;10
 (= __ (try
          (rest '())
          (catch IllegalStateException e "No dice!"))))
; pop throws exception
; rest yields an empty list
; the difference is because of the intentions of the 2 opss
 (= '() (try
          (rest '())
          (catch IllegalStateException e "No dice!")))


No comments:

Post a Comment