Enum.reduce + :lists.reverse() vs List.foldr

862 views
Skip to first unread message

mraptor

unread,
Oct 8, 2014, 12:02:39 AM10/8/14
to elixir-l...@googlegroups.com
hi,

Why would I use :
Enum.reduce + :lists.reverse()
instead of :
List.foldr

Rob Lally

unread,
Oct 8, 2014, 1:25:43 AM10/8/14
to elixir-l...@googlegroups.com
Because Enum.reduce will work on any enumerable - such as a stream, and List.foldr works on Lists.

R,


--
You received this message because you are subscribed to the Google Groups "elixir-lang-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-ta...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Onorio Catenacci

unread,
Oct 8, 2014, 9:53:26 AM10/8/14
to elixir-l...@googlegroups.com
It's also worth considering that some functions may not yield the same reduction depending on the order in which the elements are seen.  Consider this contrived example:

iex(1)> [1,2,3,4] |> List.foldr(0,&(&1 - &2))
-2

vs.

iex(2)> [1,2,3,4] |> List.foldl(0,&(&1 - &2))
2

In this particular case, Enum.reduce will act like a foldl. And I'm sure there are plenty of other operations where order of traversal of the list is going to be important as well.

FWIW.


--
Onorio

Onorio Catenacci

unread,
Oct 8, 2014, 10:52:24 AM10/8/14
to elixir-l...@googlegroups.com
Wow, I'm a bit embarrassed that I wasn't a bit more careful about replying there.

While I am sure the point about the order in which elements of a list are seen is a valid one, it looks like I've somehow set up that example incorrectly.  In this particular case, either way fold should yield -10. I'm not quite sure how I managed to flummox that up so badly.

So, anyone--please help me wipe the egg from my face--what did I do wrong in typing in those expressions?  Why did I get two different results and why did neither of them come out to -10 (seemingly the correct answer)?

--
Onorio

Peter Hamilton

unread,
Oct 8, 2014, 10:58:29 AM10/8/14
to elixir-l...@googlegroups.com

Your function is called with (el, acc), not (acc, el).

1 - 0 = 1
2 - 1 = 1
3 - 1 = 2
4 - 2 = 2

And

4 - 0 = 4
3 - 4 = -1
2 - -1 = 3
1 - 3 = -2

Onorio Catenacci

unread,
Oct 8, 2014, 11:13:55 AM10/8/14
to elixir-l...@googlegroups.com
Thanks Peter.  That makes perfectly good sense now. 
Reply all
Reply to author
Forward
0 new messages