LoginSignup
3

More than 5 years have passed since last update.

[JavaプログラマのためのHaskell]二日目・リストの話

Last updated at Posted at 2016-01-15

前回の続き.
前回出てきたリストリテラルを使って引き続きコードを書いてみます.
その前にまずは少し肩慣らしに命名規則から.

Haskellの命名規則その1


Haskellでは、ある要素とその要素のリストがあるとき、それぞれに束縛される変数名を単数形と複数形で対応させる.
例: 整数に束縛される変数n→整数のリストに束縛される変数ns
   文字に束縛される変数c→文字列に束縛される変数cs

head.hs

標準入力の最初の10行を出力.

head.hs
main = do cs <- getContents
          putStr $ firstNLines 10 cs

firstNLines n cs = unlines $ take n $ lines cs

  ・引数の関数適用: 関数名 引数1 引数2 引数3 ...
  ・関数の定義: 関数名 仮引数1 仮引数2 ... = 本体
          firstNLines関数は引数を2つ取る関数で、仮引数がnとcsである.
  ・unlines関数: lines関数の逆で、行のリストを連結して文字列にする.
           その際、各行の末尾に改行文字を付加する.

unlines ["aaa", "bbb", "ccc"] = "aaa\nbbb\nccc\n"
unlines ["aaa"]               = "aaa\n"
unlines [""]                  = "\n"
unlines []                    = ""
unlines ["aaa\n"              = "aaa\n\n"

  ・take関数: リスト先頭からn個の要素をとってリストで返す関数.
         リストの長さがnより短い時はリスト全体を返す.

take 3 [1, 2, 3, 4, 5] → [1, 2, 3]
take 3 [1]             → [1]
take 3 []              → []
take 3 "String"        → "Str"
take 0 [1, 2, 3]       → []
take (-1) [1, 2, 3]    → []

tails.hs

標準入力の最後の10行を出力.

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

lastNLines n cs = unlines $ takeLast n $ lines cs
takeLast n ss = reverse $ take n $ reverse ss

  手順は、
  1.行のリストを逆順にする.
  2.先頭からn行を取る.
  3.とった部分リストをまた逆順にする.

  ・reverse関数: リストを逆順にする.

reverse [1, 2, 3]          → [3, 2, 1]
reverse []                 → []
reverse "String"           → "gnirtS"
reverse ["aa", "bb", "cc"] → ["cc", "bb", "aa"]

words関数

文字列を空白文字で区切ってリストに分割する.

words "This is a pen." → ["This", "is", "a", "pen."]

今回はここまで!
第一回
第三回

出典
青木峰郎.ふつうのHaskellプログラミング ふつうのプログラマのための関数型言語入門.ソフトバンク クリエイティブ株式会社,2006,372p.

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3