1

有人可以帮我把这段代码转换成clojure吗

BufferedReader br = new BufferedReader(new FileReader(args[0]));

                // Read in first line, if nothing, inputString is null
                String inputString = br.readLine(); // First line is header
                inputString = br.readLine();
    while (inputString != null) {

        rowCount++;
    }

但是,我了解使用 recur 的必要性,因为我正在从文件中读取并且行数是一个不可变的值,我如何增加它以使该值在 while 循环中不断增加。

4

2 回答 2

2

如果您只需要文件中的行数,您可以这样做:

(defn count-lines[file]
  (with-open [r (clojure.java.io/reader file)]
  (count (line-seq r))))

或者,如果你想对每一行做一些事情(例如,打印它):

(defn count-lines[file]
   (with-open [r (clojure.java.io/reader file)]
    (loop [i 1
          s (line-seq r)]
          (println (first s))
          (if (seq (rest s))
           (recur (inc i) (rest s)) i))))
于 2013-01-02T05:26:22.407 回答
0
(defn read-lines [file]
  (clojure.string/split-lines (slurp file)))

; count the number of lines
(count (read-lines "c:/test.log"))

; returns a list of indexed lines
(map-indexed vector (read-lines "c:/test.log"))
;[[0 "Line 1"]
; [1 "Line 2"]
; [2 "Line 3"]
;  ...]
于 2013-01-08T14:51:19.183 回答