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

Haskell の小技 read

read を使って "1 2 3" から [1,2,3] を作る方法。

Prelude> map (\x -> read x :: Int) $ words "1 2 3"
[1,2,3]

または、

Prelude> map (read :: String -> Int) $ words "1 2 3"
[1,2,3]

2番めの方法は関数 read の型を :: で指定するという意味なのだろうか?

おまけで総和を計算してみた。

Prelude> sum $ map (read :: String -> Int) $ words "1 2 3"
6

ひょっとしたらリストを直接読み込むこともできる?

Prelude> (read :: String -> [Int]) "[1,2,3]"
[1,2,3]
Prelude> sum $ (read :: String -> [Int]) "[1,2,3]"
6

ファイルからも読み込める。

ファイル名: test.txt
1 2 3
4 5 6

Prelude> readFile "test.txt" >>= return . map (read :: String -> Int) . words
[1,2,3,4,5,6]

積算もできる。

Prelude> readFile "test.txt" >>= return . sum . map (read :: String -> Int) . words
21
by tnomura9 | 2012-07-10 05:55 | Haskell | Comments(0)
<< 相関係数 1週間で3オクターブの声が出せ... >>