chrix75
Why do we use a dot to call a function?
Hi,
I’ve started learning Elixir by reading the book Programming Elixir and I’ve got one question (at this moment
). What is the motivation for using the . character to call a function ?
It’s strange to write myFunc.() instead of myFunc(). I suppose I find that weird because of my other languages knowledge 
Most Liked
cmkarlsson
Joe Armstrong called it 
I quote:
“If you leave it like this expect to spend the next twenty years of your
life explaining why. Expect thousands of mails in hundreds of forums.”
NobbZ
You do use the dot for functions bound to variables. Not for defined functions,
iex(1)> defmodule M do
...(1)> def foo(a), do: a + 1
...(1)> end
# ...
iex(2) foo = fn a -> a + 1 end
# ...
iex(3) M.foo(1)
2
iex(4) foo.(1)
2
This is mainly to distinguish in case of nameclashes.
AstonJ
The dot is only used when calling anonymous functions that have been bound to a variable (and not functions defined inside a module). The dot also reminds us that it is an anonymous function.
This is an anonymous function:
foo = fn a -> a + 1 end
And called like this:
foo.(10)
This is a function defined inside a module:
defmodule MyModule do
def foo(a), do: a + 1
end
And called like this:
MyModule.foo(10)
If you continue reading the book Dave goes on to explain this ![]()
satom99
Just to clarify, these are refered to as anonymous functions. Which, as mentioned, are nameless and should be called using a dot and may also be defined using the & shorthand. Refer to this lesson for a better overview.
NobbZ
This is very contrived but shows my point:
defmodule M do
def foo(a) do
foo = fn b -> a + b end
# foo(1) # Nope, this will result in an infinite loop; also compiler might complain about unused variable `foo`
foo.(1) # this works!
end
end








