0

Using clojure, how do you read a file of strings and store it in an int-array or vector.

Here are my functions so far.

(:require [clojure.java.io :as io])
 (defn getData [filename]
   (doseq [line
     (with-open [rdr (io/reader filename)]
       (doall (line-seq rdr)))]
         (println line)))

(defn convert [string]
  (map #(Integer/parseInt %)
    (.split #" " string)))

I am not sure where to go from here. I have tried to call the getData function inside the convert function but have had no luck because the getData function is not returning the string.

-> (apply convert (getData "num.txt"))

2 Answers2

0

You should read some more about clojure and perhaps go over some exercises like the ones in 4clojure to sharpen your understanding a little. Your attempt is very confused, and I am not sure you understand what every line does there.

Essentially, you are looing over all lines with doseq and printing them to the screen, which returns nil. Then you try to apply convert to nil. You should do fine just returning the result of doall.

As for your convert function, you are trying to split a list of strings, you should map split over the list first, and call parseInt on the results of that. You shouldnt need to invoke it using apply, instead treat the argument as a list of strings, and it will make a little more sense.

Shlomi
  • 4,708
  • 1
  • 23
  • 32
0

First, how is your file ?

I assume it is like that

1 2 3
4 5 6
7 8 9 10

First you want to parse a line into a collection of integers (str/split is from clojure.string) :

(defn parse-line [str-line]
  (->> (str/split str-line #" " )
       (map #(Integer/parseInt %))))

Then you want to apply this to all lines an return a big array (java array ?) of integers :

(defn getData [filename]
  (with-open [rdr (io/reader filename)]
    (let [data (line-seq rdr)]
      (int-array (mapcat parse-line data)))))

If you want to have separate arrays

(defn getData [filename]
  (with-open [rdr (io/reader filename)]
    (let [data (line-seq rdr)]
      (doall (map (comp int-array parse-line) data)))))

Line-seq returns a sequence of lines. So even if you ad one line, line-seq will return a sequence containing your single line. If you want vector(s), just replace int-array by vec. For sequence(s), remove int-array.

Joseph Yourine
  • 1,301
  • 1
  • 8
  • 18