Comment by kccqzy
2 days ago
In case anyone who doesn't know Haskell: both of these are beginner level mistakes. Using `foldl` causes space leaks and turns your O(1) space algorithm to O(N) space for no good reason. And using `foldr` over lists is good when you are dealing with unevaluated lists and want list fusion, but not when they already exist in memory and will continue to do so. And that doesn't even include the obviously wrong choice of data structure, built-in Haskell lists are singly-linked lists not arrays. There are Array types and Vector types (both come with GHC so no extra dependency needed) that are more appropriate for implementing APL in the first place.
> And using `foldr` over lists is good when you are dealing with unevaluated lists and want list fusion, but not when they already exist in memory and will continue to do so.
What's the preffered approach?
I have the definitive answer to this question in my article “foldl traverses with State, foldr traverses with anything”
https://h2.jaguarpaw.co.uk/posts/foldl-traverses-state-foldr...
In short: use foldl’ when you’re iterating through a list with state. foldr can be used for anything else, but I recommend it for experts only. For non-experts I expect it’s easier to use for_. For more details about that see my article “Scrap your iteration combinators”.
https://h2.jaguarpaw.co.uk/posts/scrap-your-iteration-combin...
Is it really easier to use for_? It forces you to think about effects rather than pure data. So you end up packaging data into effects through State or similar monads. So is it really easier if you force people to use Monad (well technically Applicative)?
1 reply →
Usually you want `foldl'` (with ' at the end), the strict version of `foldl`. It prevents the creation of intermediate thunks, so effectively a tail recursive iteration over the list in constant space.
`foldr` I almost never use, but it would be for: the return value is a lazy list and I will only need to evaluate a prefix.
The naming conventions are nicely sadistic.
4 replies →