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

Function as first-class citizen

2023_12_08_1.livemd

Function as first-class citizen

Function as an argument

Enum.map([1, 2, 3], fn x -> x ** 3 end)

Function as a return value

defmodule Power do
  def of_three(list) do
    Enum.map(list, pow(3))
  end

  def of_two(list) do
    Enum.map(list, pow(2))
  end

  def pow(n) do
    fn x -> x ** n end
  end
end
Power.of_three([1, 2, 3])
Power.of_two([2, 4, 78])

Assign a function to a variable

power_of_four = Power.pow(4)
power_of_four
power_of_four.(3)
defmodule X do
  def f(y) do
    y * 3
  end
end