リストを操作する関数(その2)

2006年4月11日
1 分

zip は2つのリストからそれぞれの要素を取り出して,タプル(組)にしたリストを返す。

Prelude> zip [1,2,3] "abc"
[(1,'a'),(2,'b'),(3,'c')]

タプルには違う型を含めることができる。 zipWith はタプルを作る代わりに関数を適用する。

Prelude> zipWith (+) [1,2,3] [10,20,30]
[11,22,33]

上の例では + を zipWith の第1引数と渡しているけど,()で囲んでやらないとエラーになる。 うまく zipWith の引数として認識できないってことかな。

Prelude> zipWith + [1,2,3] [10,20,30]
<interactive>:1:10:
Couldn't match `[a]' against `t -> t1'
Expected type: [a]
Inferred type: t -> t1
Probable cause: `[1, 2, 3]' is applied to too many arguments in the call
([1, 2, 3] [10, 20, 30])
In the second argument of `(+)', namely `[1, 2, 3] [10, 20, 30]'

ところでタプルって何に使うんだろ。 追記: zipWith の引数について こうすると同じメッセージがでる。つまり二つのリストが zipWith ではなく + の引数だと解釈されてしまうってことか。

Prelude> zipWith (+ [1,2,3] [10,20,30])
<interactive>:1:11:
Couldn't match `[a]' against `t -> t1'
Expected type: [a]
Inferred type: t -> t1
Probable cause: `[1, 2, 3]' is applied to too many arguments in the call
([1, 2, 3] [10, 20, 30])
In the second argument of `(+)', namely `[1, 2, 3] [10, 20, 30]'