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

ElixirKenya - 24/09/2021

2021/elixir_kenya.livemd

ElixirKenya - 24/09/2021

Anonymous Functions

fn x -> x + 1 end
(fn x -> x + 1 end).(3)
f = fn x -> x + 1 end
f.(3)
&(&1 + 1)
(&(&1 + 1)).(3)
f = &(&1 + 1)
f.(3)
(&(&1 * &2)).(4, 5)

Not a mathematical function

Enum.shuffle([1, 2, 3])
:random.uniform()

Higher-order functions

f = fn x -> x + 1 end
list = [1, 2, 3]

Enum.map(list, f)
# new_list = [f(1), f(2), f(3)]
defmodule Higher do
  def f do
    fn x -> x + 1 end
  end
end

list = [1, 2, 3]
Enum.map(list, Higher.f())

State as a parameter

# state
# {result, state} = f(23, state)
# {result, state} = f(34, state)

f = fn x, y -> [y | x] end

[]
|> f.(3)
|> f.(4)
|> f.(5)

Currying?

f = fn x, y -> x + y end

f.(2, 3)

g = f.(2)
g.(3)

Adding a new element to the beginning of a list

list = [1, 2, 3]

[4 | list]

list ++ [4]