[Haskell-beginners] Alternative

Yitzchak Gale gale at sefer.org
Wed Dec 28 21:47:10 UTC 2016


I wrote:
>> you would want to use foldr, not foldl

Imants Cekusins wrote:
> foldl enumerates items in "natural" order:
> in [1,2] 1 is passed to the fn, then 2
> foldr on the other hand begins with 2 and ends with 1.

The list is not reversed by either one of them. And in
both of them, the first element of the list is examined
first.

With foldl, you apply the complete operation to each
element of the list in turn, all the way to the end of
the list.

With foldr, you start with the first element and say:
Let's think about what will happen when we apply
the operation to the first element with the result of
the entire fold from the second element onward.
Knowing only the first element at this time, can
we already say what the result will be?

In this case, there are two possibilities: If the first
element is Just, then yes, we already know the
result, and we can discard the rest of the fold
without ever actually computing it. If the first
element is Nothing, then we don't know the result
yet. But we do know that the first element is
irrelevant, so we discard it and move on.

Doesn't foldr seem like a more natural way to do
what you want here?

The reason this doesn't work in Erlang is
because Erlang is a strict language. When we try
to apply the operation with first parameter the first
element of the list and second parameter the rest
of the fold, Erlang does the entire calculation
of that second parameter - the entire fold - before it
even starts thinking about the operation.

Regards,
Yitz


More information about the Beginners mailing list