1
votes

I'm trying to open a text file and split it into a list of integer values in Clojure. I get this error code every single time, and I've got no idea why. I'm relatively new to Lisp development (I mean I started like two hours ago), so it might be that I'm asking a really silly question. Cheers

(ns clojure.examples.hello
  (:gen-class))

(ns clojure-noob.core)

(defn toInt [s]
  (Integer/parseInt (re-find #"\A-?\d+" s)))
(defn toIntList [s]
  (if (not s) ()
    (list* (toInt (first (toInt s)) (toIntList first((rest 
  (clojure.string/split s #" "))))))
  )
)

(println (str (toIntList (slurp "hab.txt"))))
3
Could you post a sample input like what hab.txt would contain? - Taylor Wood
just a bunch of integers separated by spaces - Márton Kardos

3 Answers

3
votes

The reason you are getting that error message is that (somewhere) you are incorrectly calling a function that expects a sequence argument with an integer argument. One place that this could be is here:

(first (toInt s))

The function first expects a sequence (ISeq), yet toInt is returning an integer.

And just to confirm:

(first (java.lang.Integer/parseInt "10"))

IllegalArgumentException Don't know how to create ISeq from: java.lang.Integer

1
votes

Assuming hab.txt is just a single line of space-delimited integers, this should work:

(defn to-int [s]
  (Integer/parseInt (re-find #"\A-?\d+" s)))
(defn parse-int-str [s]
  (map to-int (clojure.string/split s #" ")))
(println (parse-int-str "1 2 3 4 5"))
=> (1 2 3 4 5)

Or a recursive version as requested:

(defn parse-int-str [s]
  (loop [nums []
         strs (clojure.string/split s #" ")]
    (if (seq strs)
      (recur (conj nums (to-int (first strs)))
             (rest strs))
      nums)))

You could do this without loop/recur but you risk exhausting stack space. You could also think about doing this with reduce.

0
votes

Let's prepare a file:

(spit "foo.txt" "  3 5  662 35 3  ")

Now let's read the file, split the string by empty symbols, remove empty ones and parse them into integers. The code

(as->
   "foo.txt" $ 
   (slurp $)
   (clojure.string/split $ #"\s+")
   (remove empty? $)
   (mapv #(java.lang.Integer/parseInt %) $))

gives

[3 5 662 35 3]