More Related Content
More from Takashi Kawachi
More from Takashi Kawachi (6)
Haskell超初心者勉強会11
- 3. 入力ストリーム
•getContents :: IO String
•一度に全てを読み込まない。
メモリを食いつぶさない。
文字列(文字リスト)を遅延評価する。
import Data.Char
main = do
contents <- getContents
putStr $ map toUpper contents
Monday, July 29, 13
- 4. ファイルの読み込み
•hFoo は Handle を引数に取る関数
•hGetContents は stdin の代わりに
handle から読み込む
•遅延評価
import System.IO
main = do
handle <- openFile “baabaa.txt” ReadMode
contents <- hGetContents handle
putStr contents
hClose handle
Monday, July 29, 13
- 9. readFile
•readFile :: FilePath -> IO String
•開いて読んで閉じる
import System.IO
main = do
contents <- readFile “baabaa.txt”
putStr contents
Monday, July 29, 13
- 20. 正格 vs 遅延
• 正格 bytestring (Data.ByteString)
• thunk なし
• 最初のバイトを評価する時、全体を評価
• 遅延 bytestring (Data.ByteString.Lazy)
• 64KB chunk 毎に評価される
• 64KB は L2 cache にフィットする
良いサイズ
Monday, July 29, 13
- 21. pack/unpack
•リストと相互変換
•Word8 は 8 bits unsigned int
pack :: [Word8] -> ByteString
unpack :: ByteString -> [Word8]
> import qualified Data.ByteString.Lazy as B
> let x = B.pack [99, 97, 110]
> x
“can”
> B.unpack x
[99, 97, 110]
Monday, July 29, 13
- 23. bytestring モジュール
の関数
• Data.List と似た関数
• head, tail, init, null, length, map, foldl,
foldr, concat, takeWhile, filter など
• http://hackage.haskell.org/package/
bytestring/
• System.IO と似た関数
• readFile :: FilePath -> IO ByteString など
Monday, July 29, 13