In Elixir, a common practice is to use anonymous functions. Creating an anonymous function is simple:
iex(1)> my_func = fn x -> x * 2 end
#Function<6.52032458/1 in :erl_eval.expr/5>
The general syntax is:
fn args -> output end
For readability, you may put parenthesis around t...
Use keyword lists for 'options'-style parameters that contains multiple key-value pairs:
def myfunc(arg1, opts \\ []) do
# Function body
end
We can call the function above like so:
iex> myfunc "hello", pizza: true, soda: false
which is equivalent to:
iex> myfunc("he...
Named Functions
defmodule Math do
# one way
def add(a, b) do
a + b
end
# another way
def subtract(a, b), do: a - b
end
iex> Math.add(2, 3)
5
:ok
iex> Math.subtract(5, 2)
3
:ok
Private Functions
defmodule Math do
def sum(a, b) do
a...
Elixir matches a function call to its body based on the value of its arguments.
defmodule Math do
def factorial(0): do: 1
def factorial(n): do: n * factorial(n - 1)
end
Here, factorial of positive numbers matches the second clause, while factorial(0) matches the first. (ignoring negat...
Guard clauses enables us to check the arguments before executing the function. Guard clauses are usually preferred to if and cond due to their readability, and to make a certain optimization technique easier for the compiler. The first function definition where all guards match is executed.
Here is...
You can pass default parameters to any named function using the syntax: param \\ value:
defmodule Example do
def func(p1, p2 \\ 2) do
IO.inspect [p1, p2]
end
end
Example.func("a") # => ["a", 2]
Example.func("b", 4) # => ["b", ...
Use & to capture functions from other modules. You can use the captured functions directly as function parameters or within anonymous functions.
Enum.map(list, fn(x) -> String.capitalize(x) end)
Can be made more concise using &:
Enum.map(list, &String.capitalize(&1))
Captu...