『ふつうのHaskellプログラミング』 の第2章を参考にして wc コマンドっぽいのを書いてみた。

ソースコード。標準入力を読み込んで、行数、単語数、文字数をカウントするプログラム。


$ cat ./mywc.hs
main = do hoge <- getContents
          print $ countlines hoge
          print $ countwords hoge
          print $ countchars hoge
 
countlines x = length $ lines x
countwords x = length $ words x
countchars x = length x

読みこませるテキストファイル。


$ cat ./a.txt
This is a pen.
これはペンです。

プログラムを実行。mywc の標準入力にテキストファイルをリダイレクトで接続する。


$ runghc ./mywc.hs < ./a.txt
2
5
24

行数2、単語数5、文字数24(改行コードを含む)と出力された。

Ref. wc (UNIX) - Wikipedia

tags: haskell

Posted by NI-Lab. (@nilab)