Haskell を使ってみる 2 (リストの操作)

前回の続き

Haskell を使ってみる 1 (導入) - kntmr-blog

リスト同士の連結

++ 演算子は2つのリストを引数に取る。第1引数に指定したリストは最後まで走査されるため、要素数が大きいリストを扱う場合は注意が必要。

Prelude> [1,2,3,4] ++ [5,6,7,8]
[1,2,3,4,5,6,7,8]
Prelude> "Hello" ++ " " ++ "Haskell" -- 文字列は文字のリストとして表される
"Hello Haskell"

Prelude> [1,2,3,4] ++ 5 -- これはエラー

<interactive>:20:1: error:
    • Non type-variable argument in the constraint: Num [a]
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        it :: forall a. (Num [a], Num a) => [a]

Prelude> [1,2,3,4] ++ [5] -- これはOK
[1,2,3,4,5]

リストの先頭に要素を追加

: 演算子の第1引数は、追加するリストの要素と同じ型の単一の要素。

Prelude> 4 : [1,2,3]
[4,1,2,3]
Prelude> 'x' : "abcde"
"xabcde"

リストの要素にアクセス

Prelude> [1,2,3,4,5] !! 1
2
Prelude> "Hello Haskell" !! 4
'o'

リスト同士の比較

先頭の要素から辞書順に比較される。

Prelude> [1,2,3] < [1,2,5]
True
Prelude> ['a','b','x'] < ['a','b','c']
False
Prelude> "Hello" == "Hello"
True

その他のリスト操作

Prelude> head [1,2,3,4,5]
1
Prelude> tail [1,2,3,4,5]
[2,3,4,5]
Prelude> last [1,2,3,4,5]
5
Prelude> init [1,2,3,4,5]
[1,2,3,4]
Prelude> head [] -- 空のリストでは使えない
*** Exception: Prelude.head: empty list

Prelude> length [1,2,3,4,5]
5
Prelude> null [1,2,3,4,5] -- リストが空かどうか
False
Prelude> null []
True

Prelude> reverse [1,2,3,4,5]
[5,4,3,2,1]

Prelude> take 3 [1,2,3,4,5] -- 先頭から指定された数の要素を取り出してリストで返す
[1,2,3]
Prelude> drop 2 [1,2,3,4,5] -- 先頭から指定された数の要素を除いたリストを返す
[3,4,5]

Prelude> maximum [3,2,5,1,4] -- 辞書順で最も大きい要素を返す
5
Prelude> minimum [3,2,5,1,4] -- 辞書順で最も小さい要素を返す
1

Prelude> sum [1,2,3,4,5] -- 要素の和を返す
15
Prelude> product [1,2,3,4,5] -- 要素の積を返す
120

Prelude> elem 2 [1,2,3,4,5] -- 指定された要素がリストに含まれているか
True
Prelude> elem 9 [1,2,3,4,5]
False

elem は中置関数として用いられることが多い。

Prelude> 3 `elem` [1,2,3,4,5]
True

今回はリストの操作まで。