프로그래밍/Clojure

[Brave Clojure #5] 챕터 4 연습문제

김재택 2023. 12. 20. 19:00

챕터 4 연습문제를 풀었습니다.

;;; ex 4.1
(def result (glitter-filter 3 (mapify (parse (slurp filename)))))

(map :name result)
;; => ("Edward Cullen" "Jacob Black" "Carlisle Cullen")


;;; ex 4.2
(defn append
  [[car & cdr] new-suspect]
  (if car
    (cons car (lazy-seq (append cdr new-suspect)))
    (list new-suspect)))

(append '() 1)
;; => (1)

(append '(1 2 3 4) 5)
;; => (1 2 3 4 5)

;;; ex 4.3
(def validators {:name string? :glitter-index int?})
(defn validate
  [val-fn-map record]
  (reduce #(and %1 %2)
          (map (fn [[key value]]
                 ((key val-fn-map) value))
               record)))

(validate validators {:name "hello" :glitter-index "no"})
;; => false
(validate validators {:name "hello" :glitter-index 123})
;; => true
(validate validators {:name 321 :glitter-index 123})
;; => false

;;; ex 4.4
(def columns [:name :glitter-index])
(def inversions {:name identity
                 :glitter-index str})
(defn map-to-row [mp]
  (clojure.string/join
   ","
   (map #((% inversions) (% mp))
        columns)))

(defn back-to-csv [list-of-maps]
  (clojure.string/join
   "\n"
   (map map-to-row
        list-of-maps)))

(back-to-csv (mapify (parse (slurp filename))))
;; => "Edward Cullen,10\nBella Swan,0\nCharlie Swan,0\nJacob Black,3\nCarlisle Cullen,6"
(slurp filename)
;; => "Edward Cullen,10\nBella Swan,0\nCharlie Swan,0\nJacob Black,3\nCarlisle Cullen,6"