What are the types of functions in Elixir?

Function

A function is a piece of organized, well-structured, and reusable code used to perform specific tasks or actions.

Note: Pass some input to a function, and it will generate an output against it.

Function f takes an input x and outputs f(x)

Types of functions

In Elixir, there are three types of functions:

  • Named functions
  • Anonymous functions
  • Pattern matching functions

Named function

A named function is a simple function defined using def. It is defined within a defmodule block and can be called with reference to the module name.

Example

Below is an example of a named function:

defmodule Math_func do
def exp(x, y, z) do
mul = x * y
mul + z
end
end
IO.puts "evaluation of the expression 5 x 6 + 20 is "
IO.puts(Math_func.exp(5, 6, 20))

Anonymous function

An anonymous function is a one-line function and is defined using fn and end. It is similar to the lambda function and follows the pattern parameters -> function body.

Example

Below is an example of an anonymous function:

mul = fn (x, y) -> x * y end
IO.puts "multiplication of 5 x 6 is "
IO.puts mul.(6, 5)

Pattern matching function

Pattern matching function checks all possible matches in this function and executes the first match that exists. It is also defined using fn.

Example

Below is an example of a pattern-matching function:

result = fn
{var1} -> IO.puts("#{var1} I found 1st match!")
{var_2, var_3} -> IO.puts("#{var_2} #{var_3} I found 2nd match!") # first match for two arguments
{var_2, var_3} -> IO.puts("#{var_2} #{var_3} I found 3rd match!")
end
result.({"Hey"}) # passing one argument
result.({"Hello", "azee"}) # passing two arguments

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved