Functions

Elixir Functions

Defining Elixir Functions

Elixir functions use def and defp with pattern matching.

Defining Functions with def

In Elixir, functions are defined using the def keyword. These functions are public and can be accessed from outside the module. Let's see a basic example of how to define a function in Elixir.

In the example above, we defined a module named Math and a public function add/2 that takes two parameters and returns their sum. The function is accessible from outside the module, allowing other modules or scripts to call Math.add/2.

Defining Private Functions with defp

Elixir also allows the definition of private functions using the defp keyword. Private functions can only be called within the module they are defined in.

In this example, subtract/2 is a private function, and it's used within the difference/2 function. This demonstrates how private functions work within a module to perform internal operations.

Pattern Matching in Function Definitions

One of Elixir's powerful features is pattern matching, which can be used in function definitions to control function behavior based on argument patterns.

Here, the greet/1 function matches the input string to determine which greeting to return. If the input doesn't match any specified language, it falls back to a default case.

Using Guards in Function Definitions

Guards are additional conditions used to further refine pattern matching in functions. Let's look at an example:

In this example, guards are used to determine if a number is positive, negative, or zero. The guards when number > 0 and when number < 0 refine the function's pattern matching to execute only when the conditions are true.