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.
In Elixir, there are three types of functions:
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.
Below is an example of a named function:
defmodule Math_func dodef exp(x, y, z) domul = x * ymul + zendendIO.puts "evaluation of the expression 5 x 6 + 20 is "IO.puts(Math_func.exp(5, 6, 20))
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.
Below is an example of an anonymous function:
mul = fn (x, y) -> x * y endIO.puts "multiplication of 5 x 6 is "IO.puts mul.(6, 5)
Pattern matching function checks all possible matches in this function and executes the first match that exists. It is also defined using fn.
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!")endresult.({"Hey"}) # passing one argumentresult.({"Hello", "azee"}) # passing two arguments
Free Resources