takeWhileRight
Keeps the longest run at the end of a source where a predicate holds, in source order.
Lecture
takeRight takes the last
n elements; takeWhileRight takes the last elements
that match, however many that turns out to be. It is to
takeRight what takeWhile
is to take — a predicate where the
other wanted a count.
Only a run that reaches the very end counts. If the last element already fails, the result is empty no matter how long a matching run sat just before it. That is what makes it a suffix operator rather than a "longest match anywhere" search.
The result comes back in source order, not reversed, so
it chains with everything else in the library and lines up with
dropWhileRight — together
the two split a source in half with nothing lost or repeated.
Nothing can be emitted before the source ends: until the last element has
arrived, no element is known to belong to the suffix. Over a
List the trailing run is found by walking backwards from the
end, so the predicate only ever sees that run; over any other source
every element is tested in order and the current run is buffered. Keep
the predicate pure and the difference will not reach you.
Demo 1 · Basics
Demo 2 · Async, and the split
Try it yourself
Exercise: keep only the trailing run of readings at or above 30.
dropWhileRight — the complement: drop that same run ·
takeRight — a trailing slice by count ·
takeWhile — the same idea from the front ·
filter — matches anywhere, not just at the end