Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Functions, modules, and pattern matching

ElixirZone_Vegalite.livemd

Functions, modules, and pattern matching

Anonymous functions

fn num -> num + 7 end
&(&1 + 7)
(fn num -> num + 7 end).(10)
(&(&1 + 7)).(10)
(fn a, b, c -> a + b + c end).(30, 30, 40)
(&(&1 + &2 + &3)).(300, 300, 400)
add_7 = fn num -> num + 7 end
add_7.(8)

Modules & (named) functions

defmodule MyModule do
end
defmodule MyModule do
  def add_2(num), do: 2 + num

  def add_3(num) do
    3 + num
  end
end
MyModule.add_2(4)
MyModule.add_3(9)
alias MyModule, as: M

M.add_3(5)
import MyModule

add_3(7)

The pipeline operator, |>

7 |> add_3() |> add_2()
7 |> (&add_3/1).() |> (&add_2/1).()
7 |> (&(&1 + 3)).() |> (&(&1 + 2)).()
7
|> (&(&1 + 3)).()
|> (&(&1 + 2)).()
7
|> add_3()
|> add_2()

Multi-clause functions with pattern-matching

defmodule Greeting do
  def greet(:professor_williams), do: "Hello, Professor Williams"

  def greet(:mom), do: "Hi, Mom!"

  def greet(:best_friend), do: "Yo! Wassup?!?!"
end
alias Greeting, as: G

G.greet(:professor_williams) |> IO.inspect()
G.greet(:mom) |> IO.inspect()
G.greet(:best_friend) |> IO.inspect()