The import
command in Elixir allows the use of functions and macros from other modules without having to name the module. In other words, this command enables writing function arg
instead of module.function arg
. This is useful when a function is used frequently in code.
The following example shows how to import the Enum
module and use the sort function without typing in Enum.sort
:
import EnumIO.inspect sort([4,2,8,5,30,1])
Import can also be used to import a single module using the only:
option:
import Enum, only: [sort: 1]IO.inspect sort([4,2,8,5,30,1])
Here, only the sort/1
function has been imported from the Enum module. Functions can also be left out from imported modules using except:
.
import Enum, except: [sum: 1]IO.inspect sort([4,2,8,5,30,1])
import Enum, except: [sum: 1]IO.puts sum([4,2,8,5,30,1])
By running these examples, it can be seen that the sort function works, but the sum function doesn’t when the sum has been excluded.
Free Resources