Best Way To Extract Data From Lazy Sequence

74 views
Skip to first unread message

octopusgrabbus

unread,
Jun 28, 2011, 8:42:28 AM6/28/11
to Clojure
Given this test program:

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

(defn process-file
"Process csv file and prints first item in every row"
[file-name]
(let [data (slurp file-name)
rows (parse-csv data)]
(dorun (map #(println (first %)) rows))))

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

is it reasonable to write a recursive function that takes the lazy
sequence -- rows -- (returned from clojure-csv) and column numbers and
recurses until the appropriate column number is reached, or is it
better to build up a long series of expressions that would pull the
columns out?

For example, I believe I can pull out the second column by specifying
(first (next rows)), but it would look pretty awful to create a long
enough expression to get the 6th column in.

Alex Robbins

unread,
Jun 28, 2011, 9:01:00 AM6/28/11
to clo...@googlegroups.com
If you are trying to get the 6th row, you might use the "nth"
function. It allows you to grab an element based on its index. That'd
be better than tons of (next (next (next rows))) stuff.

user=> (doc nth)
-------------------------
clojure.core/nth
([coll index] [coll index not-found])
Returns the value at the index. get returns nil if index out of
bounds, nth throws an exception unless not-found is supplied. nth
also works for strings, Java arrays, regex Matchers and Lists, and,
in O(n) time, for sequences.

Alex

> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clo...@googlegroups.com
> Note that posts from new members are moderated - please be patient with your first post.
> To unsubscribe from this group, send email to
> clojure+u...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en

octopusgrabbus

unread,
Jun 28, 2011, 2:39:11 PM6/28/11
to Clojure
Thanks. That works perfectly.
(ns test-csv
(:gen-class)
(:use clojure.contrib.command-line)
(:use clojure-csv.core))

(defn x1
[val1 val2]
(println val1 val2))

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

(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)))

On Jun 28, 9:01 am, Alex Robbins <alexander.j.robb...@gmail.com>
wrote:
Reply all
Reply to author
Forward
0 new messages