偶数のリストいろいろ

定義。

even1 = [2,4..]
even2 = filter (\x -> x `mod` 2 == 0) [1..]
even3 = filter (\x -> x `mod` 2 /= 1) [1..]
even4 = zipWith (+) [1..] [1..]
even5 = map (\x -> x * 2) [1..]
even6 = 2:(map (2+) even6)
even7 = map (\x -> sum $ replicate x 2) [1..]
even8 = scanl (\x y -> x + y) 2 $ repeat 2
even9 = scanl1 (\x y -> x + y) $ repeat 2
even10 = map (\x -> sum $ take x $ repeat 2) [1..]
even11 = map (\x -> length $ replicate (x*2) "Haskell") [1..]
even12 = iterate (2+) 2

結果。

*Main> take 20 $ even1
[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
*Main> take 20 $ even2
[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
*Main> take 20 $ even3
[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
*Main> take 20 $ even4
[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
*Main> take 20 $ even5
[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
*Main> take 20 $ even6
[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
*Main> take 20 $ even7
[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
*Main> take 20 $ even8
[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
*Main> take 20 $ even9
[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
*Main> take 20 $ even10
[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
*Main> take 20 $ even11
[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
*Main> take 20 $ even12
[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]

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

foldl と foldr はちょっとわかりにくい。なのでこんなのを書いてみた。
括弧内の数字は引数を表している。0 が初期値で 1, 2, 3… がリストの各要素。内側の括弧から順に評価される。
foldl はこう。

*Main> foldl (\x y -> "(" ++ x ++ "," ++ y ++ ")" ) "0" ["1","2","3","4","5"]
"(((((0,1),2),3),4),5)"

で foldr はこう。

*Main> foldr (\x y -> "(" ++ x ++ "," ++ y ++ ")" ) "0" ["1","2","3","4","5"]
"(1,(2,(3,(4,(5,0)))))"

何となくわかりやすい……?