Clojureで単語を数える

一時間で覚える Rubyを見習い、
ファイル内の単語数を数えるコマンド、wcを作ってみます。

;word-count.clj
(use 'clojure.contrib.duck-streams)
(use 'clojure.contrib.str-utils)

(defn read-words [path]
  (for [line (read-lines path) word (re-split #"\s" line)] word))

(println 
  (count (for [f *command-line-args*
               word (read-words f)]
           word)))

メモ

clojure.contrib

clojure.contribは、使用頻度が高い基本的な関数を大量に含んだライブラリです。

  1. リファレンス
  2. ダウンロード先

使用するときは、clojure-contrib.jarにクラスパスを通す必要があります。

>java -cp clojure.jar;clojure-contrib.jar clojure.main

と、コマンドラインで与えるか、環境変数で指定しましょう。

read-lines

ファイルを開き、行のシーケンスを返す関数。
clojure.contrib.duck-streamsにあります。

re-split

正規表現で文字列を分離する関数。
clojure.contrib.str-utils

*command-line-args*

コマンドライン引数が格納されたシーケンスです。

count

シーケンスの長さを返します。
無限シーケンスに使うと固まります。