Is there a name for a recursion scheme that's like a catamorphism, but that allows peeking at the final result while it's still running? Here's a slighly contrived example:
toPercents :: Floating a => [a] -> [a]
toPercents xs = result
where
(total, result) = foldr go (0, []) xs
go x ~(t, r) = (x + t, 100*x/total:r)
{-
>>> toPercents [1,2,3]
[16.666666666666668,33.333333333333336,50.0]
-}
This example uses total at each step of the fold, even though its value isn't known until the end. (Obviously, this relies on laziness to work.)
Though this is not necessarily what you were looking for, we can encode the laziness trick with a hylomorphism:
This corresponds to the laziness trick because, thanks to hylo fusion, the intermediate
CappedListnever actually gets built, andtoPercentsconsumes the input list in a single pass. The point of usingCappedListis, as moonGoose puts it, placing the sum at the bottom of the (virtual) intermediate structure, so that the list rebuilding being done withpercAlgcan have access to it from the start.(It is perhaps worth noting that, even though it is done in a single pass, it seems difficult to get nice-and-constant memory usage from this trick, be it with my version or with yours. Suggestions on this front are welcome.)