In Elixir, multiple expressions can be delimited by semicolon (;
).
Elixir complains in below function definition
defmodule Module2 do
def func([c], n), do: IO.inspect(c); c + n
end
with error
** (CompileError) hello.exs:2: undefined function c/0
(stdlib) lists.erl:1352: :lists.mapfoldl/3
(stdlib) lists.erl:1352: :lists.mapfoldl/3
(stdlib) lists.erl:1353: :lists.mapfoldl/3
However, Elixir is happy with below syntax.
defmodule Module1 do
def func([c], n) do
IO.inspect(c); c + n
end
end
I am not sure why one works over the other - as far as I understand both styles of function definition are equivalent.
Complete code below for reference
defmodule Module1 do
def func([c], n) do
IO.inspect(c); c + n
end
end
defmodule Module2 do
def func([c], n), do: IO.inspect(c); c + n
end
Module1.func('r', 13)
Module2.func('r', 13)
If you really must do this, you will need to use parentheses:
defmodule Module2 do
def func([c], n), do: (IO.inspect(c); c + n)
end
The problem with the original is the precedence of ;
vs function/macro calls, because of which it is parsed like this:
defmodule Module2 do
(def func([c], n), do: IO.inspect(c)); c + n
end
You can verify that this gives the exact same error you mention - the compiler naturally complains because you're trying to use c
outside of the context of the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With