Education‎ > ‎Closer to Clojure‎ > ‎

Closer to Clojure 09: I/O

Function println prints out to standard output by default. The following code shows how to redirect the standard output to "my.log".

(binding [*out* (java.io.FileWriter. "my.log")]
  ; ...
  (println "This goes to the file my.log.")
  ; ...
  (flush))

Function flush flushes buffer. Function print and println take arbitrary number of parameters. Function println prints strings and then puts LF, flushes the buffer. You can concat strings by (str exp1 exp2... ).

Function line-seq returns lazy-evaluated sequence of all lines of the buffer specified by java.io.BufferReader.

(defn print-if-contains [line word]
  (when (.contains line word) (println line)))

(let [file "story.txt"
    word "fur"]
  (with-open [fr (java.io.FileReader. file)
      br (java.io.BufferedReader. fr)]
    (doseq [line (line-seq br)]
      (print-if-contains line word))))

Macro doseq provides similar feature of 'for' of bash or Python.

Reference:
http://java.ociweb.com/mark/clojure/article.html
println関数はデフォルトで標準出力に書き出します.次のコードは出力先を "my.log" ファイルに変更します.

(binding [*out* (java.io.FileWriter. "my.log")]
  ; ...
  (println "This goes to the file my.log.")
  ; ...
  (flush))

flush関数は文字通りバッファのフラッシュです.printおよびprintln関数は任意個の引数をとります.printlnはprintした後に改行文字を印刷し,バッファをフラッシュします.文字列をつなぎたいときは (str exp1 exp2 ...) を使います.

line-seq 関数は java.io.BufferedReader で指定されたバッファのすべての行の遅延評価シーケンスを返します.

(defn print-if-contains [line word]
  (when (.contains line word) (println line)))

(let [file "story.txt"
    word "fur"]
  (with-open [fr (java.io.FileReader. file)
      br (java.io.BufferedReader. fr)]
    (doseq [line (line-seq br)]
      (print-if-contains line word))))

マクロdoseqはbashやPythonのfor文のようなものです.

参考
http://java.ociweb.com/mark/clojure/article.html
Comments