Avoiding reduce

I saw an interesting comment today in stackoverflow that one would use reduce to get a single value and map to produce a sequence.  I took the comment to mean, you would not use reduce to select columns from a sequence. (In fairness a comment came in after I originally wrote this post which indeed indicated reduce could be used the way I want to.) I have not been able to figure out how map could be used to take a vector of vectors — parsed by clojure-csv — walk through each row, and apply a list or vector of columns numbers to produce a smaller csv row.

I have a recent post about Reducing The Reduction, and this is a follow-up on that. So, I’ve reduced one reduce by using a list comprehension (for). It works quite nicely. The problem with my examples, is I have to doctor up the data, because the data is proprietary.


(defn reduce-csv-rowF
  "Accepts a csv-row and a list of columns to extract, and
   reduces the csv-row to the selected list using a list comprehension."
  [csv-row col-nums]
  (for [col-num col-nums
     :let [part-row (nth csv-row col-num nil)]]
   part-row))
(defn reduce-csv-row
"Accepts a csv-row and a list of columns to extract, and
reduces the csv-row to the selected list."
[csv-row col-nums]
(reduce
(fn [out-csv-row col-num]
(let [out-val (nth csv-row col-num nil)]
(conj out-csv-row out-val)))
[]
col-nums))

(defn out-csv
  "Accepts a lazy-seq parsed by ret-csv-file and returns a smaller file that
   was reduced by the cols-select argument."

  [all-csv-rows cols-select]
  (reduce
    (fn [out-csv-rows one-csv-row]
      (let [reduced-row (reduce-csv-row one-csv-rowX cols-select)]
        (conj out-csv-rows reduced-row)))
    []
    all-csv-rows))
Advertisements

Leave a comment

Filed under Clojure

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