Modules and Functions in Elixir
Following the previous post you should be able to start an iex session and drop some Elixir lines in there.
Now we are gonna see how we can organize our code; A good way to achieve this is using Modules.
Let’s create a new file called animal.ex with the following code:
defmodule Animal do
def make_sound(sound) do
IO.puts(sound)
end
end
There are a couple of things going on here so let’s see it line per line.
The first line is the module definition defmodule … do and for the name we usually go with CamelCase.
The second line defines a function inside the module, it should be pretty familiar if you know your ruby/python.
The third line prints to the terminal the given parameter here we don’t have a plain puts attached to a global object, instead we need to call the IO module and his puts method.
Now we can do:
iex animal.ex
That should pick our file, compile and then open the interactive shell:
Erlang/OTP 18 [erts-7.1] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
Interactive Elixir (1.1.1) — press Ctrl+C to exit (type h() ENTER for help)
iex(1)>
Let’s go ahead and try the Animal module:
iex(1)> Animal.make_sound(‘cuack’)
cuack
:ok
Here we are calling the make_sound method of the Animal module, on the next line we have our message printed and the final line shows the IO.puts output ( we are gonna see more about that :ok later on)
That’s our first module there are some other ways to work with them like defining namespaces.
Let’s check some examples
defmodule Animal.Cat do
def meow do
IO.puts('meow')
end
end
defmodule Animal.Dog do
def bark do
IO.puts('bark')
end
end
If you are familiar with ruby this should be analogous to do Animal::Dog and Animal::Cat this it’s just to get our code in order between namespaces, we could also do
defmodule Animal do
defmodule Dog do
...
end
defmodule Cat do
...
end
end
and it should have the same effect.
Next post we are gonna check some other things about functions.