LYH 9.1 ファイルとストリーム
問題
(1) foreverについて、型シグネチャと用途、importすべきものを言え。
(2) toUpperについて、importすべきものを言え。
(3) capslocker.hsを実装せよ。
(4) getContentsは遅延I/Oであり、入力が大きい場合は( )消費量の面で有利である。
(5) contents <- getContents
によって、contentsにgetContentsの結果が束縛されるとき、最終的に文字列として評価される( )としてメモリ上に置かれる。
(6) 10文字より短い行だけ出力するプログラムを作れ。
(7) interactとはどのような関数か。
(8) inretactを用いて、入力した文字列の回文判定をせよ。
解答
(1)
forever :: Applicative f => f a -> f b Source #
- forever act repeats the action infinitely.
- Control.Monad
(2) Data.Char
(3)
import Control.Monad import Data.Char main = forever $ do l <- getLine putStrLn $ map toUpper l
import Data.Char main = do contents <- getContents putStr $ map toUpper contents
(4) メモリ消費量
(5) プロミス(promise)
(6)
main = do contents <- getContents putStr (shortLinesOnly contents) shortLinesOnly :: String -> String shortLinesOnly = unlines . filter (\line -> length line < 10) . lines
main = interact shortLinesOnly shortLinesOnly :: String -> String shortLinesOnly = unlines . filter (\line -> length line < 10) . lines
(7) 入力を文字列として受け取り、それを関数で変換し、結果を出力する
(8)
respondPalindromes :: String -> String respondPalindromes = unlines . map (\xs -> if isPal xs then "palindrome" else "not palindrome") . lines isPal :: String -> Bool isPal xs = xs == reverse xs
感想
遅延I/Oすごい。おかげで対話的なプログラムでも入力をEOFまで読み込んだと考えてコードを書くことができる。 promiseって、JSのpromiseとかdeferredとかと関係ある?