← All languages
Haskell function of the day
Random

scanr

Right scan producing intermediate accumulator values.

Description

scanr is the right-to-left analogue of scanl. Its type signature is (a -> b -> b) -> b -> [a] -> [b]. It returns a list of intermediate results from folding the list from the right, ending with the initial value.

scanr f z [x1, x2, ..., xn] produces [f x1 (f x2 (... (f xn z) ...)), ..., f xn z, z]. The last element of the result is always the initial value z. Like scanl, scanr reveals all intermediate accumulator states.

Unlike scanl, scanr processes the list from right to left and is not suitable for infinite lists. It is useful when the fold direction matters, such as building right-associated structures.

Arguments

NameDescriptionOptional
f A binary function (a -> b -> b) to apply at each step. No
z The initial accumulator value. No
xs The list [a] to scan over. No

Example

scanr (+) 0 [1, 2, 3, 4]    -- [10, 9, 7, 4, 0]
scanr (\x acc -> x : acc) [] [1, 2, 3]
-- [[1,2,3],[2,3],[3],[]]

Reference