> In the examples given I can't see how they are different from using reduce
> with a tuple as an accumulator, eg:
>
> ```
> for i <- [1, 2, 3], reduce: {0, 0}  do
>   {doubled, sum} -> {i * 2, i + sum}
> end
> ```
>

There is some confusion here. "reduce" cannot return the modified list, so
the example above is not doing what you expect it to. However, let's assume
you want to write this instead:

for i <- [1, 2, 3], reduce: {0, 0}  do
  {count, sum} -> {count + 1, i + sum}
end

Then you are right, they are not different. In the reduce case, it is a
different syntax to achieve the same thing. So you may ask: why change?

I think there are two benefits to the proposed syntax:

1. Collocating variable declaration with initialization

In your example, you need pass the initial value in one place and then the
names they receive is elsewhere:

for i <- [1, 2, 3], reduce: {0, 0}  do
  {count, sum} -> {count + 1, i + sum}
end

For example, we could change it to this to address this issue:

for i <- [1, 2, 3], reduce: {count, sum} = {0, 0}  do
  {count + 1, i + sum}
end

2. By declaring the variables that are part of reduce prior to the
generators, they can be used as part of the filters. So we can further
change the code above to this:

for reduce {count, sum} = {0, 0}, i <- [1, 2, 3]do
  {count + 1, i + sum}
end

And that would allow us to, for example, count only the first 100:

for reduce {count, sum} = {0, 0}, count < 100, i <- [1, 2, 3] do
  {count + 1, i + sum}
end

Furthermore, I would say declaring reduce upfront is better, because you
don't need to read all generators and filters to figure out what the
comprehension will actually return.

So there is more we can do with the new syntax, but from the point of view
of inputs/outputs, they are equivalent. The implicit variable assignment is
gone. The only downside of the proposed syntax compared to the current one
is that the current one makes it easier if you want to have multiple
clauses. But it is not such a common case and you could use a "case ... do"
as well.

In other words, even if we are not to add "for let", I would say this
version of reduce is superior and it should be considered in itself.

-- 
You received this message because you are subscribed to the Google Groups 
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to elixir-lang-core+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/elixir-lang-core/CAGnRm4LmhgA%3De9_vZ8_1eyv3gjsUsArYZH31388s-%3D%2BY-uUM5Q%40mail.gmail.com.

Reply via email to