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? Well, you might have tried $ elixir mymath.exs
but that probably didn't do anything interesting...
The answer lies in importing the module in an interactive session. First, make sure your working directory is the same as the directory you...