Reputation: 11
So basically my question is I was trying to read a data from a text file which is numbers like this: "1 5 3 8 9 3 23 67 90" and i wanted to read them number by number and put this in a list or a vector or array. However this is my first time coding with Clojure and that is why i am asking this question.
what i did so far is this which i am sure it is not correct.
(def nums11 (slurp "C:\\Users\\XXX\\Desktop\\100.txt"))
However this will only read the file as one string. so i decided to add this line
(clojure.string/split nums11 #" ")
is there any way to add them, after i split them, into a list or a vector or array.
or maybe there is an easy way to do this?
Thanks in advance.
Upvotes: 1
Views: 1172
Reputation: 3346
You are in the right path already, so I'll try to explain what's next:
The function clojure.string/split
returns a vector
of Strings. The vector in Clojure is a collection that implements the Java interface java.util.List
so you are done if all you needed was to turn the contents of the file into a collection of Strings representing the numbers (to turn these into actual numbers, read on).
Probably you want to manipulate the elements as actual numbers. In Clojure, you'll need to use some function to turn each String into a number (say "34"
into the actual number 34). There are two simple ways: using Java interop and call Integer.parseInt(...)
or use a function provided by Clojure that is able to read a String and return a whatever it represents (eg. read-string
).
Since we need to call a function (read-string
) to every element of the list of Strings representing numbers, we'll use map
, a function that takes a function f
and a collection xs
, and calls a the function f
on every element of xs
, returning the result as another list.
If we glue it all together, it will be something like the following (I'll use let
to give names to the intermediate results):
(let [file-contents (slurp "C:\\Users\\XXX\\Desktop\\100.txt")
nums-as-strings (clojure.string/split file-contents #" ")
numbers (map read-string nums-as-strings)]
... here the list of numbers will be on numbers
; and now you can perform operations on them, such as summing all of them:
(reduce + numbers) ;; Compute the sum of all the numbers
There are a number of small details that I've glossed over, but this should put you in the right track.
Upvotes: 3