loop時に前後の値を参照する
例えば、隣接する要素同士の和のリストを返す関数を考える
例えば[1..5を与えた時
[3,5,7,9]を返す
通常の再帰関数のとき
x1:x2:xsのようにすれば良いだけ
code:hs
pairs :: Int -> Int
pairs (x1:x2:xs) = x1+x2 : pairs (x2:xs)
pairs _ = []
他の例
2023/8/15 Acronym#64db2c911982700000f21878
foldと併用する時
(1個前の値,結果) -> 現在の値 -> (次に渡す現在の値,結果)
(a,[a])という型
code:hs
keepPair :: (Int, Int) -> Int -> (Int, Int)
keepPair (0, xs) c = (c, xs)
keepPair (l, xs) c = (c, xs ++ l+c)
(aの単位元,[])を与えてスタートする
code:hs
pairsFold :: Int -> Int
pairsFold = snd . foldl keepPair (0, [])
他の例
2023/8/15 Acronym#64db2c871982700000f21877
関連
lookAhead
Paramorphism