Haskell を使ってみる 4 (タプル)

前回の続き

Haskell を使ってみる 3 (リスト内包表記) - kntmr-blog

タプル

タプルは、複数の異なる型の要素を格納することができる。タプルは括弧で囲む。

Prelude> (1,3)
(1,3)
Prelude> (1,'a',"Hello")
(1,'a',"Hello")

サイズ2のタプルはペアと呼ばれる。サイズ3のタプルはトリプルと呼ばれる。タプルはサイズが固定で、ペアとトリプルは異なる型として扱われる。ペアとトリプルを混在させるとエラーになる。

Prelude> [(1,2),(4,5,6),(8,9)]

<interactive>:13:8: error:
    • Couldn't match expected type ‘(t, t1)’
                  with actual type ‘(Integer, Integer, Integer)’
    • In the expression: (4, 5, 6)
      In the expression: [(1, 2), (4, 5, 6), (8, 9)]
      In an equation for ‘it’: it = [(1, 2), (4, 5, 6), (8, 9)]
    • Relevant bindings include
        it :: [(t, t1)] (bound at <interactive>:13:1)

サイズが同じで要素の型が異なるタプルは区別される。

Prelude> [(1,2),(1,'a')]

<interactive>:15:5: error:
    • Could not deduce (Num Char) arising from the literal ‘2’
      from the context: Num t
        bound by the inferred type of it :: Num t => [(t, Char)]
        at <interactive>:15:1-15
    • In the expression: 2
      In the expression: (1, 2)
      In the expression: [(1, 2), (1, 'a')]

タプル (ペア) を操作する関数

Prelude> fst (1,2) -- 1つ目の要素を返す
1
Prelude> snd ('a', 'b') -- 2つ目の要素を返す
'b'
Prelude> zip [1,2,3] ["one","two","three"] -- 2つのリストを受け取りタプルのリストを作成する
[(1,"one"),(2,"two"),(3,"three")]

zip 関数は異なる型のリストを受け取れるため、リストのサイズが異なる場合はサイズが小さい方のリストに合わせられる。また、遅延評価なので有限リストと無限リストを zip することができる。

Prelude> zip [1,2,3,4,5] ["one","two","three"]
[(1,"one"),(2,"two"),(3,"three")]
Prelude> zip [1..] ["one","two","three"]
[(1,"one"),(2,"two"),(3,"three")]

空のタプル ()ユニットと呼ばれる。


今回はタプルのところだけ。