Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - Multiple expressions on same line - Compiler error when using do: syntax in function definition

Tags:

elixir

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)
like image 373
Wand Maker Avatar asked Aug 01 '15 16:08

Wand Maker


Video Answer


1 Answers

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.

like image 140
Paweł Obrok Avatar answered Sep 28 '22 01:09

Paweł Obrok