有没有一种递归方案的名称,类似于catamorphism,但允许在它仍在运行时查看最终结果?以下是一个稍微牵强的例子:
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]
-}
这个示例在fold的每个步骤中使用total
,即使它的值直到最后才知道。(显然,这取决于惰性才能工作。)