Sebb
Comprehension syntax
I can do:
if true, do: :foo, else: :bar
and:
if true do
:foo
else
:bar
end
And I can do:
for i <- 0..3, do: {i, i+i}, into: %{}
but not:
for i <- 0..3 do
{i, i+i}
into
%{}
end

why is that?
Marked As Solved
hauleth
Because else got special treatment to ease user experience. This sugar is not available for any other atom outside the small set of predefined ones (else, rescue, catch, and after).
Also Liked
josevalim
You can, you have to pass them before the do.
for …, into: %{} do
…
end
hauleth
That is not true. Both are exactly the same thing for the compiler:
iex(1)> quote do
...(1)> if true do
...(1)> :foo
...(1)> else
...(1)> :bar
...(1)> end
...(1)> end
{:if, [context: Elixir, import: Kernel], [true, [do: :foo, else: :bar]]}
iex(2)> quote do
...(2)> if(true, [do: :foo, else: :bar])
...(2)> end
{:if, [context: Elixir, import: Kernel], [true, [do: :foo, else: :bar]]}
hauleth
As I said, it is literally impossible to define for in Elixir. I meant that do: 10 and do … end aren’t really treated differently just for for, but the same rules applies to all calls.
for is special form not because of do but because each x <- y is separate argument, so for i <- 1..10, do: i is 2-ary function and for i <- 1..10, j <- 1..10, do: i + j is 3-ary function. So either for would need to have N different heads and just fail in case if someone would like to use more than that, then it would fail (see older Rust compilers to see that problem, there Debug is defined only up to 32-ary tuples, as there is no variadic generics). Due that problem for and with must be defined as special forms, because they require parser magic to be then expanded properly.
Sebb
So I can’t use into, uniq, reduce in a for ... end block?
chungwong
if true, do: :foo, else: :bar
and:
if true do
:foo
else
:bar
end
are different, although they look similar.
The first form is actually a if macro accepting two arguments.
if(true, [do: :foo, else: :bar])
And to make the second form works, we need a into macro which I don’t think we have it.







