[Haskell-beginners] Alternative

Imants Cekusins imantc at gmail.com
Wed Dec 28 20:43:25 UTC 2016


> you would want to use foldr, not foldl

foldl vs foldr baffles me a bit.

in Erlang http://erlang.org/doc/man/lists.html#foldl-3
use of *foldl* is suggested. I got used to this and usually use foldl.

another reason is: it appears that in Haskell - same as Erlang - *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.

however: *foldr* arg order: a -> acc  is more natural.

I very rarely deal with large lists and never (so far) with inifinites.

for this case for which I consider and use Alternatives - the list would be
2 - 5 items long. The order though is important.

>>> asum [Just 1, Just 2]
Just 1
>>> asum [Nothing, Just 1, Nothing, Just 2, Nothing]
Just 1

looks "naturally" ordered: tested left to right.

I may not understand the workings (memory and such) of foldl vs foldr
however I hope that for small lists it is sufficient to focus on the order
of element processing.

order matters. This example hopefully confirms that foldr begins @ end,
foldl begins @ start. Same as in Erlang ;)

Prelude Data.Foldable> *foldr* (\i1 acc1 -> i1 + acc1 * 2) 0 [1,2]
5
Prelude Data.Foldable> *foldl* (\acc1 i1 -> i1 + acc1 * 2) 0 [1,2]
4
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20161228/c88d6194/attachment.html>


More information about the Beginners mailing list