How does scanr work? Haskell
scanr
is to foldr
what scanl
is to foldl
. foldr
works from the right:
foldr (+) 0 [1,2,3] =
(1 + (2 + (3 + 0))) =
(1 + (2 + 3)) =
(1 + 5) =
6
-- [ 6, 5, 3, 0 ]
and scanr
just shows the interim results in sequence: [6,5,3,0]
. It could be defined as
scanr (+) z xs = foldr g [z] xs
where
g x ys@(y:_) = x+y : ys
scanl
though should work like
scanl (+) 0 [1,2,3] =
0 : scanl (+) (0+1) [2,3] =
0 : 1 : scanl (+) (1+2) [3] =
0 : 1 : 3 : scanl (+) (3+3) [] =
0 : 1 : 3 : [6]
so it must be that
scanl (+) z xs = foldr f h xs z
where h z = [z]
f x ys z = z : ys (z + x)