人気ブログランキング | 話題のタグを見る

フィルターを作る

interact 関数で簡単にフィルターを作ることができるのが分かったので作ってみた。

interact 関数は引数に、String -> String 型の関数をとり、この型の関数ならば何でもフィルターにしてくれる。前回の cat は次のように一行でフィルターが作れた。

main = interact id

実行例
>caT < caT.hs
main = interact id

>caT
banana
banana
apple
apple
orange
orange
^Z

ファイルを文字列でソートする関数 mysort は次のように記述できる。

-- filename mysort.hs
module Main where

import Data.List (sort)

main = interact (unlines . sort . lines)

実行例
>mysort < mysort.hs


-- filename mysort.hs
import Data.List (sort)
main = interact (unlines . sort . lines)
module Main where

ファイルの列の順序を反対にする関数 reverse は次のようになる。

-- filename "reverse.hs"
module Main where

main = interact (unlines . reverse . lines)

実行例
>reverse < reverse.hs
main = interact (unlines . reverse . lines)

module Main where
-- filename "reverse.hs"

フィルター・プログラムに関して言えば、Haskell が一番作るのが簡単だ。
by tnomura9 | 2011-10-05 10:50 | Haskell | Comments(0)
<< モナドでモジュール化(1) id 関数 >>