Clojure 1.3:
user> (require '[clojure.java [io :as io]]) nil user> (line-seq (io/reader "foo.txt")) ("foo" "bar" "baz") user> (into #{} (line-seq (io/reader "foo.txt"))) #{"foo" "bar" "baz"}
line-seq
gives you a lazy sequence in which every element in the sequence is a line in the file.
into
dumps all this into a set. To do what you tried to do (add each element one at a time), rather than doseq
and refs, you can do:
user> (reduce conj #{} (line-seq (io/reader "foo.txt"))) #{"foo" "bar" "baz"}
Note that Unix comm
compares two sorted files, which is probably a more efficient way to compare files than doing intersection sets.
Edit: Dave Ray is right, to avoid leaking open files, it is better to do this:
user> (with-open [f (io/reader "foo.txt")] (into #{} (line-seq f))) #{"foo" "bar" "baz"}
source share