今日の自作関数

今日の自作関数は,foldr.


とりあえずこれで動くかな?と書いたもの.

foldr' :: (a -> b -> b) -> b -> [a] -> b
foldr' f b [] = b
foldr' f b (x:xs) = foldr' f (f x b) xs

hugsで動かす.

Main> foldr (/) 2 [8,12,24,4]
8.0
Main> foldr' (/) 2 [8,12,24,4]
0.5

うぅん,ちゃんと動かない.


なんというか,

it takes the second argument and the last item of the list and applies the function, then it takes the penultimate item from the end and the result, and so on.

がイマイチ和訳できないから仕組みがわかんない.


ちらっとカンニング

foldr' :: (a -> b -> b) -> b -> [a] -> b
foldr' f b [] = b
foldr' f b (x:xs) = f x (foldr' f b xs)

はぁ,こういう仕組みになっているのですか.なるほど.ともかく,実行.

Main> foldr' (/) 2 [8,12,24,4]
8.0

お,動いた.