Re:It never makes sense to use foldl on lists in Haskell (2019)
by Ericson2314 on Friday March 20, 2020 @09:06PM
(#22643360)
foldl' is fine an Haskell, and one of 2 endorsed by this.
[ Parent
| on HN ]
Re:It never makes sense to use foldl on lists in Haskell (2019)
by dependenttypes on Saturday March 21, 2020 @12:57AM
(#22644574)
Note that you need to import Data.List if you want to use foldl'
(and chances are that you will still leak memory like crazy)
Re:It never makes sense to use foldl on lists in Haskell (2019)
by nimih on Saturday March 21, 2020 @02:26AM
(#22644938)
Out of curiosity, what causes foldl' to leak memory in most cases? I generally use it out of habit if I know I will consume the entire list and don't have a good reason to use foldr, so it would be nice to know if I'm shooting myself in the foot.
Re:It never makes sense to use foldl on lists in Haskell (2019)
by 08-15 on Saturday March 21, 2020 @05:11AM
(#22645426)
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)
Re:It never makes sense to use foldl on lists in Haskell (2019)
by dependenttypes on Saturday March 21, 2020 @05:24AM
(#22645457)
{-# LANGUAGE Strict, StrictData, BangPatterns #-} should imply the !, right?
Re:It never makes sense to use foldl on lists in Haskell (2019)
by 08-15 on Saturday March 21, 2020 @05:46AM
(#22645523)
I 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.)