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 ![]()
Last Post!
NobbZ
I do use them as I need them and I like the erlang and elixir way.
In go code I write for work when I have a long function body in legacy code I often see foo() and then searching begins… My first reaction is scanning the list of functions on the right, but it’s not there. Then I scroll up to the current functions head to see if it is passed in as an argument, I don’t even find it there so I scroll even more up and see a dot imported package… I hate this ambiguity…
In elixir and erlang I can see at least if it is a variable or a “real” function.
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










