foldRight
Reduces from the last element to the first — the right-associative counterpart of fold.
Lecture
For an associative step — +, max, string
concatenation — direction does not matter and
fold is all you need. For everything
else it decides the answer. fold nests from the left, so
[1, 2, 3] with subtraction is
((0 - 1) - 2) - 3; foldRight nests from the
right and gives 1 - (2 - (3 - 0)).
The natural use is building something that wraps: a nested structure, a chain of decorators, a linked list where each step has to hold the rest of the result. Written as a left fold those come out inside-out.
The reducer keeps fold's (acc, element) argument
order rather than Haskell's foldr flip, so the same callback
works with either direction and you can switch one for the other without
rewriting it.
foldRightWithIndex reports each element's position in the
source, so the last element arrives first carrying the
highest index — the same number
foldWithIndex would give that
element. The reversed walk is deliberately not renumbered 0, 1,
2: an index that means different things in different operators is worse
than one that counts down.
Both are strict where fold is not. Walking backwards means
knowing where the end is, so a source that isn't a List is
materialized first and foldRightAsync drains the stream
before it starts — never point it at an infinite source.
Demo 1 · Direction changes the answer
Demo 2 · With the index, and async
Try it yourself
Exercise: describe a pipeline as nested calls, outermost step first.
fold — the same reduction from the left ·
reduce — seeded from the first element ·
foldWithIndex — the left fold with positions ·
reverse — the other way to walk backwards