からだのブログ

五体満足に生まれてきたことに感謝してブログの名前を「からだ」にしました。

からだのブログ header image 2

WordCount.scala

5月 15th, 2011 · 2 Comments · programming, Scala

stdin からの入力に含まれる「単語」を辞書順に並べて、出現した行番号と一緒に出力するプログラム。Scala で。

object WordCount extends Application {
  val lines = io.Source.fromInputStream(System.in).getLines

  val dict = (for((line, i) <- lines.zipWithIndex;
      word <- """(\w+)""".r.findAllIn(line)) yield (word, i+1)
  ).toList.groupBy {  _._1 }

  dict.keys.toList.sorted foreach { key =>
    println("%-16s%s".format(key, dict(key) map { _._2 } mkString(" ")))
  }
}

実行例。

Tags: