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

ヒストグラム その2

ヒストグラムを作成するプログラムができたので、テキストファイルからデータを読み書きできるようにした。単純化のためデータは Int 型のリストに統一した。リストのデータはテキストファイルには改行区切りの数字の文字列にした。この形のテキストデータは、エクセルのカラムにコピペできるし、その逆もできる。


1.Histogram モジュールのソースコード


Histogram モジュールのプログラムは次のようになる。

module Histogram where

toint :: [String] -> [Int]
toint = map (read :: String->Int) . (filter (/=""))



fromFile :: String -> IO [Int]
fromFile fname = readFile fname >>= return . toint . lines

histogramM :: [Int] -> [Int] -> IO [Int]
histogramM bin = return . (histogram bin)

toFile :: String -> [Int] -> IO ()
toFile fname = (writeFile fname) . unlines . (map show)



count :: (Int, Int) -> [Int] -> Int
count (lo, hi) = length . filter (\x -> (lo<=x) && (x<hi))

bins :: [Int] -> [(Int, Int)]
bins lst = zip lst (tail lst)

histogram :: [Int] -> [Int] -> [Int]
histogram bin lst = map ((flip count) lst) $ bins bin


2.Histogram モジュールの使い方


Histogram モジュールは ghci のプロンプトから :load コマンドで読み込む。

Prelude> :load Histogram.hs
[1 of 1] Compiling Histogram ( Histogram.hs, interpreted )
Ok, modules loaded: Histogram.
*Histogram>

toint 関数は ["12", "34"] のような文字列の配列を [12, 34] のような整数のリストに変換するサポート関数だ。

*Histogram> toint ["1","2","","3"]
[1,2,3]

fromFile 関数は改行区切りのテキストデータを読んで整数のリストに変換する関数だ。引数 fname はファイル名で、値は IO [Int] 型だからこれは IO モナドの関数だ。

*Histogram> fromFile "data.txt"
[2,3,4,5,6,7,3,4,5,6,7,8,4,5,6,7,8,9,5,6,7,8,9,10,6,7,8,9,10,11,7,8,9,10,11,12]

histogramM 関数は [1..10] のようなインターバルのリストを引数に取り、第二引数の [Int] 型のデータのヒストグラムを作成して IO [Int] 型のデータを返す。IO [Int] 型のデータを返すのでこれも IO モナド型の関数だ。

*Histogram> histogramM [1..5] [2,2,3,3,1,3,4,4,1,3]
[2,2,4,2]

toFile 関数の引数 fname はファイル名で、[Int] 型のリストを第二引数に取り、ファイルに改行区切りの文字列として出力する。

*Histogram> toFile "data2.txt" [1..5]
*Histogram> readFile "data2.txt"
"1\n2\n3\n4\n5\n"

fromFile 関数、histogramM 関数、toFile 関数を >>= でパイプすると "data.txt" のデータのヒストグラムを作って "data2.txt" に出力できる。

*Histogram> fromFile "data.txt" >>= histogramM [2..13] >>= toFile "data2.txt"
*Histogram> fromFile "data2.txt"
[1,2,3,4,5,6,5,4,3,2,1]

IO モナド型の関数を作っておくと、Unix のパイプラインのように情報処理を関数の組み合わせで行うことができる。

by tnomura9 | 2015-10-02 21:42 | Haskell | Comments(0)
<< 型クラス制約 Type Cla... ヒストグラム >>