Welcome! Please see the About page for a little more info on how this works.

+1 vote
in Syntax and reader by

My code :

(defn loadData [filename]
(with-open [rdr (io/reader filename)]

(doseq [line (line-seq rdr)
        :let [ [id & data]
              (clojure.string/split line #"\|")] ]
            [
                (Integer/parseInt id) 
                data 
              ])
  
  ))

My file's content:

1|Xxx|info1|222-2222
2|Yyy|info2|333-3333
3|Zzz|info3|444-4444

How do I get this function to return a list like :
{
{1, Xxx, info1, 222-2222}
{2, Yyy, info2, 333-3333}
{3, Zzz, info3, 444-4444}
}

1 Answer

+1 vote
by
selected by
 
Best answer

So, I think the main thing here is that doseq returns nil, not a list.

Perhaps something like this will get you started...

file.txt:

1|Xxx|info1|222-2222
2|Yyy|info2|333-3333
3|Zzz|info3|444-4444

Then, in the REPL:

user> (defn load-data
        [filename]
        (with-open [r (clojure.java.io/reader filename)]
          (-> (for [line (line-seq r)]
                (let [[id name info phone] (clojure.string/split line #"\|")]
                  [(Integer/parseInt id) name info phone]))
              (doall))))
#'user/load-data
user> (load-data "file.txt")
([1 "Xxx" "info1" "222-2222"]
 [2 "Yyy" "info2" "333-3333"]
 [3 "Zzz" "info3" "444-4444"])

Notably, the doall is necessary here, since for returns a lazy sequence; without the doall, with-open will close the reader before anything is read.

by
How about if I want to look for let's say the vector [2 (Sue Jones 43 Rose Court Street 345-7867)]? Do you have any idea how can I proceed? I've been looking for a way to return a specific vector by providing the number (first element of the vector) but still stuck...
Thanks!
by
There are many ways - what have you tried? The simplest might be to use `filter` and `first`.
...