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
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.
Last Post!
lud
Ok so it is not defined as a special form just for the arity problem, but otherwise it is just what I said, basically it is a special form because it requires special treatment at the compiler level.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









