Haskell 写経

cat.hs(p.28)

ファイルの内容を出力する。

main = do cs <- getContents
          putStr cs

実行。

$ ghc cat.hs -o cat
$ ./cat < cat.hs
main = do cs <- getContents
          putStr cs

 

countline.hs(p.36)

ファイルの行数を出力する。

main = do cs <- getContents
          print $ length $ lines cs

lines 関数は文字列を行のリストに分割する。
実行。

$ ghc countline.hs -o countline
$ ./countline < cat.hs
2

 

head.hs(p.44)

ファイルの最初の数行(この場合は 5行)を出力する。

main = do cs <- getContents
          putStr $ firstNLines 5 cs

firstNLines n cs = unlines $ take n $ lines cs

unlines 関数は lines 関数の逆で、行のリストを連結して文字列にする。その際に各行の末尾に改行文字を付加する。
実行。

$ ghc head.hs -o head
$ ./head < fizzbuzz.hs
fizzbuzz :: Int -> String
fizzbuzz n
    | fizz && buzz = "FizzBuzz"
    | fizz         = "Fizz"
    | buzz         = "Buzz"

 

tail.hs(p.49)

ファイルの末尾数行を出力する。

main = do cs <- getContents
          putStr $ lastNLines 5 cs

lastNLines n cs = unlines $ takeLast n $ lines cs

takeLast n ss = reverse $ take n $ reverse ss

reverse 関数はリストを逆順にする。
実行。

$ ./tail < fizzbuzz.hs
    | buzz         = "Buzz"
    | otherwise     = show n
    where fizz = n `mod` 3 == 0
          buzz = n `mod` 5 == 0

 

練習問題(p.53) countbyte.hs

標準入力から読んだバイト数を数える。

main = do cs <- getContents
          print $ length cs

"abc" と ['a', 'b', 'c'] が等しいことを使う。
実行。

$ ./countbyte < cat.hs
48

 

練習問題(p.53) countword.hs

標準入力から読んだ単語数を数える。

main = do cs <- getContents
          print $ length $ words cs

words 関数は文字列を単語のリストに分割する。区切りは空白文字。
実行。

$ ./countword < cat.hs
8

 
 

ふつうのHaskellプログラミング ふつうのプログラマのための関数型言語入門

ふつうのHaskellプログラミング ふつうのプログラマのための関数型言語入門