What is the difference between Reduce and Foldl in Elixir?

Asked

Viewed 67 times

1

I found myself needing a job reduce (for having more custom with JS this is the first name that comes to mind) in the Elixir and found the Enum.reduce/2, but with a little more research already in the list module I found the List.foldl/2, from what I’ve seen they look identical to me.

Is there any difference between them?

  • Did the answer resolve what was in doubt? Do you need something else to be improved? Do you think it is possible to accept it now?

  • Opa, sorry, the doubt had been more something that appeared to me at the time was not something much that I cared that I even ended up forgetting her hehe. But confirming the case I put in the comment I can accept it.

1 answer

1

Reduce uses the first element of the sequence as a starting point in what it will do. Fold has an initial value passed to begin with. So if you’re going to add all elements of a collection and you want the initial value to be 0, both will give the same result, but if you want it to start at a different value you can only do it with foldl. Of course, for this example it is possible to add up this initial value, but there are cases that what you are doing does not work well so. In most cases just want to go through the elements and deal with them, so the reduce is more common. The type can provide one or the other, as you can see in these examples.

  • Hmm, actually that shouldn’t be it, because in the reduce, i can also set an initial value with the reduce/3 https://hexdocs.pm/elixir/Enum.html#reduce/3 , but it was my mistake, there is no foldl/2 only foldl/3, I got confused. But then the only difference is the type? The foldl is for lists and the reduce more generic because it belongs to the module Enum?

  • In the specific case there is not even one in certain collections of data and the other does not exist in others, but what really different should be this that I told you.

  • What do you mean in the specific case? Is there any formal definition of the word? About the types said that the Enum works with structures that use the Enum or Stream protocol, while the Lists, only the List type (not "enumerable") ... Until then, your reply was no longer useful

  • But that’s the difference, maybe you wanted to know something that’s not in the question.

  • What definition? My question was simple and direct, is there a difference? Of course it would be nice to see what the difference is, but what you showed me wasn’t one, the discussion below that showed one of them, and maybe it’s the only one. reread your answer and see that it does not answer me, or rather, it responds, but it is not correct (and I have no way to remove the point). The only mistake I had in the question was the arity of 2 in the foldl that doesn’t exist, and maybe that caused the problem in your answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.