5 ms·
Foldl' doesn't leak, but it sure looks like it does, if you think the folded function is strict in the accumulator argument, but isn't. For example, this atte
by 08-15 7y ago
Foldl' doesn't leak, but it sure looks like it does, if you think the folded function is strict in the accumulator argument, but isn't.
For example, this attempt at computing the average of a list
uncurry (/) . foldl' (\(s,l) x -> (s+x,l+1)) (0,0)
leaks, because during the recursion, there is no reason to scrutinize the intermediate pairs. This version is fine:
uncurry (/) . foldl' (\(!s,!l) x -> (s+x,l+1)) (0,0)
- dependenttypes 7y ago{-# LANGUAGE Strict, StrictData, BangPatterns #-} should imply the !, right?
- 08-15 7y agoI don't think it does. 'Strict' doesn't add an implicit ! to nested patterns (so (s,l) becomes !(s,l), not (!s,!l)), and 'StrictData' doesn't change anything about the tuple, which comes from a different module. (Disclaimer: I haven't actually used 'Strict', this is my interpretation of the user guide.)
- nimih 7y agoThanks, this is a helpful example :)