There are lots of good questions and answers about foldl
, foldr
, and foldl\'
in Haskell.
So now I know that:
1) foldl<
I'm still looking for an example where evaluating the combining function more eagerly would lead to a different result
The general rule of thumb is never, ever use foldl
. Always use foldl'
, except when you should use foldr
. I think you know enough about foldl
to understand why it should be avoided.
See also: Real World Haskell > Functional Programming # Left folds, laziness, and space leaks
However, your question neglects foldr
. The nifty thing about foldr
is that it can produce incremental results, while foldl'
needs to traverse the entire list before yielding an answer. This means that foldr
's laziness allows it to work with infinite lists. There are also questions and answers that go into detail about this sort of thing.
Having brought that up, let me try to succinctly answer your questions.
1) why does reduction have to occur after all thunk-ing?
Reduction only occurs at strictness points. Performing IO, for example, is a strictness point. foldl'
uses seq
to add an additional strictness point that foldl
does not have.
2) why isn't foldl evaluated just like foldl'? Is this just an implementation side-effect?
Because of the additional strictness point in foldl'
3) from the definition, foldl looks like a tail-recursive function to me -- how can I tell whether a function will actually be efficiently evaluated? It seems like I have to start worrying about order-of-evaluation in Haskell, if I don't want my program to crash.
You need to learn a little bit more about lazy evaluation. Lazy evaluation is not exclusive to Haskell, but Haskell is one of the very, very few languages in which laziness is the default. For a beginner, just remember to always use foldl'
and you should be fine.
If laziness actually gets you into trouble someday, that is when you should probably make sure you understand laziness and Haskell's strictness points. You might say that said theoretical day is a strictness point for lazy-by-default learning.
See also: PLAI > Part III: Laziness