O'Reilly logo

Learning Elixir by Kenny Ballou

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Named functions

Named functions, unlike anonymous functions, require a module for definition. That is, to define a named function we must define the function inside a module.

Here, we combine what we learned about modules and anonymous functions a bit, and we define our square function again, though, this time, we define it inside a module named MyMath. Go ahead and create a file called mymath.exs and put the following code into it:

defmodule MyMath do

  def square(x) do
    x * x
  end

end

Here, we are simply defining a function, square, which takes a single element, and returns the result of x * x. This really looks not much different from our previous versions except for being defined inside a module.

How do we run this module and see whether it works? ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required