Importing and Using Named Functions
Learn more about Elixir's named functions: how to import and use them.
We'll cover the following...
Importing named functions
The named functions we created work just like Elixir’s provided functions. We can call any named function using the pattern ModuleName.name_of_the_function
. Depending on the module we’re creating, writing ModuleName
all the time can be repetitive. We can reduce the code using the import
directive. It works like the Kernel functions; we don’t need to type the module’s name before every function name. Elixir imports all Kernel facilities to our programming environment by default.
Let’s see how we can use the import directive to create a module that stores a list of tasks in a file. Since we’ll have file manipulation, we’ll use the File module. Let’s create a file called task_list.ex
:
defmodule TaskList do@file_name "task_list.md"def add(task_name) dotask = "[ ] " <> task_name <> "\n"File.write(@file_name, task, [:append])enddef show_list doFile.read(@file_name)endendTaskList.add("task123")IO.inspect TaskList.show_list
The TaskList
module adds tasks and lists them. The add
function creates a task by appending a line with its name to a file. The function show_list
reads the file contents. Don’t worry now about show_list
’s ugly output and the errors encountered if we try to read a file that doesn’t exist. ...