Clojure: Storing Data for Later Use

One of the biggest hurdles I’ve encountered learning Clojure is when to traverse a sequence or merely to apply a function to it, like zipmap. The other hurdle is how to populate local variables properly in a let statement.

The program I am designing to learn Clojure reads a .csv file filled with water meter data. My goal is to extract a premise id and reading, and do something with that data. The premise id is in column 12, zero-indexed at all, and reading is at column 2, zero-indexed by 1.

zipmap takes the values derived from the two map statements, and creates a sequence of values, which is what I wanted. The read-map value can be passed on to other functions.

This solution came from clojure Google group. Enroute to this solution, I tried various ways to populate the map variable, and these did not work or generated a compile-time error. It would be good for someone to write a cookbook that discussed pulling data out of files and storing it in different ways in local variables.


(ns test-csv

(:gen-class)
  (:use clojure.contrib.command-line)
  (:use clojure-csv.core))

  (defn process-file
    "Process csv file and prints a column in every row"
    [file-name]
    (let [data (slurp file-name)
          rows (parse-csv data)
          read-map (zipmap (map #(nth % 11 nil) rows) (map #(nth % 1 nil) rows))]
    (println read-map)))

(defn -main [& args]
    (with-command-line args
     "Get csv file name"
     [[file-name ".csv file name" "resultset.csv"]]
     [[file-name ".csv file name" 1]]
     (println "file-name:", file-name)
     (process-file file-name)))
Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s