Comment by itishappy
2 days ago
> 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?
2 days ago
> 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)?
Yes, absolutely, I would say for almost every programmer, certainly for me. "Scrap your iteration combinators" goes into more detail. foldl' is a bit too simple to replace with for_, but for almost every other use case, yes, I do use for_. In fact, I find it remarkably liberating compared to the "iteration combinator" conventional wisdom that has been passed down from Haskeller to Haskeller over the years.
I don't feel that monads are particularly complicated. I have several non-Haskellers programming in Haskell at work, using monads. They just think they're writing a sequence of statements. I feel that mixing monads is complicated, which is why I recommend an IO-wrapper effect system (Bluefin or effectful), so that you don't need to mix.
https://h2.jaguarpaw.co.uk/posts/scrap-your-iteration-combin...
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.
This is what happens when you let Mathematicians name things on chalkboards. They don't want to run out of chalk and they get tired of spelling whole words very easily so they use short names and silly symbols. The name foldl' is "just" "fold left prime". Remember ' means "prime" from calculus class and thinking that was silly even then? Accidentally infected Haskell at a young age.
3 replies →