Search code examples
clojure

A Vampire Data Analysis Program for the FWPD, Clojure for the Brave and True


I am trying to understand the program "A Vampire Data Analysis Program for the FWPD" at the end of the 4th chapter in the book "Clojure for the Brave and True". Here is the code:

(ns fwpd.core)

(def filename "suspects.csv")

(def vamp-keys [:name :glitter-index])

(defn str->int
  [str]
  (Integer. str))

(def conversions {:name identity
              :glitter-index str->int})

(defn convert
   [vamp-key value]
  ((get conversions vamp-key) value))

(defn parse
  "Convert a CSV into rows of columns"
  [string]
  (map #(clojure.string/split % #",")
   (clojure.string/split string #"\n")))

(defn mapify
  "Return a seq of maps like {:name \"Edward Cullen\" :glitter-index 10}"
  [rows]
 (map (fn [unmapped-row]
     (reduce (fn [row-map [vamp-key value]]
               (assoc row-map vamp-key (convert vamp-key value)))
             {}
             (map vector vamp-keys unmapped-row)))
   rows))

(defn glitter-filter
  [minimum-glitter records]
  (filter #(>= (:glitter-index %) minimum-glitter) records))

Can somebody help about conversions and convert function?


Solution

  • conversions is a map, and as such contains key value pairs, called map-entries. get is a function that allows you to get the respective value returned when all you have is a key, and of course the map. So for convert to do its job then vamp-key must be either :name or :glitter-index (as they are the only keys on the map). Lets assume it is :glitter-index and that str->int is returned. Thus:

    ((get conversions vamp-key) value))
    

    , becomes:

    (str->int value)
    

    So vamp-key is needed to obtain the correct function to convert the value. If :glitter-index and "10" are the arguments passed into the function then 10 will be returned.