On Jun 11, 3:42 pm, Chouser <chou...@gmail.com> wrote:
> On Thu, Jun 11, 2009 at 3:03 PM, Adrian
>
>
>
> Cuthbertson<adrian.cuthbert...@gmail.com> wrote:
>
> > Here's a fuller example of similar techniques extracted from a working
> > program. It reads a file of lines and applies some transformations and
> > accumulates a vector of records which it finally returns;
>
> > (defn some-fn
> > "Read a file and return a vector of its records."
> > [fpath]
> > (let
> > [r (BufferedReader. (FileReader. (File. fpath)))]
> > (try
> > (let [line (.readLine r)] ; discard line 1
> > (loop [line (.readLine r) recs []]
> > (if-not line recs
> > (let [rec (do-something-with line)
> > newrecs (conj recs rec)]
> > (recur (.readLine r) newrec)))))
> > (finally
> > (.close r)))))
>
> To test this I'm using:
>
> (import '(java.io File FileReader BufferedReader))
> (defn do-something-with [line] (.toUpperCase line))
>
> Note that (let [r ...] (try ... (finally (.close r)))) is
> already packaged up in the with-open macro:
>
> (defn some-fn
> "Read a file and return a vector of its records."
> [fpath]
> (with-open [r (BufferedReader. (FileReader. (File. fpath)))]
> (.readLine r) ; discard line 1
> (loop [line (.readLine r) recs []]
> (if-not line
> recs
> (let [rec (do-something-with line)
> newrecs (conj recs rec)]
> (recur (.readLine r) newrecs))))))
>
> Also note that this is a great candidate for line-seq:
>
> (defn some-fn
> "Read a file and return a vector of its records."
> [fpath]
> (with-open [r (BufferedReader. (FileReader. (File. fpath)))]
> (vec (map do-something-with
> (next ; discard first line
> (line-seq r))))))
>
> --Chouser
Yea, I think conj was what I was looking for.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@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+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---